题目描述:

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1
/ \
2 2
\ \
3 3
说明: 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

思路解析:

思路一:对二叉树进行中序遍历,判断节点值是否对称分布(LeetCode测试用例未通过,但本地测试通过)

    public static boolean isSymmetric(TreeNode root) {

        List<Integer> res = new ArrayList<>();

        dfsTraverse(root, res);

        return validate(res);
} private static boolean validate(List<Integer> res) { for (int i = 0; i < res.size() / 2; i++) {
if (!res.get(i).equals(res.get(res.size() - 1 - i))) {
return false;
}
}
return true;
} private static void dfsTraverse(TreeNode root, List<Integer> res) { if (root == null) {
res.add(Integer.MAX_VALUE);
return;
}
dfsTraverse(root.left, res);
res.add(root.val);
dfsTraverse(root.right, res);
}

思路二:递归

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { public static boolean isSymmetric(TreeNode root) { if (root == null) {
return true;
} return validate(root.left, root.right);
} private static boolean validate(TreeNode pNode, TreeNode qNode) { if (pNode == null && qNode == null) {
return true;
}
if (pNode != null && qNode != null && pNode.val == qNode.val) { return validate(pNode.left, qNode.right) && validate(pNode.right, qNode.left); } else {
return false;
}
}
}

最新文章

  1. static变量引起的问题,List数据覆盖
  2. 从 github 执行 git clone 一个大的项目时提示 error: RPC failed
  3. 【转】C++ 单例模式
  4. dell 交换机 双链路冗余
  5. Android样式的编写格式
  6. supervisor的集中化管理搭建
  7. 用python脚本获取运行环境中的module 列表
  8. Nginx, HTTPS的配置
  9. 【模板】倍增+Floyd
  10. Matlab-11:Gausssidel迭代法工具箱
  11. centos记录uptime,tomcat日志切割,远程拷贝日志脚本
  12. PowerDesigner 教程
  13. LInux内核分析--使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
  14. Java保存文本文件
  15. 如何防止网页被植入广告,内容被监控-HTTPS
  16. 使用T-SQL导入多个文件数据到SQL Server中
  17. Thrift Expected protocol id ffffff82 but got 0
  18. SqlServer2012数据导入
  19. 赋予Winform程序管理员访问权限
  20. linux下构建SVN

热门文章

  1. pthread 编程基础
  2. 如何成为优秀的技术Leader
  3. VC文件扩展名
  4. IPhone中H5页面用on绑定click无效的解决方法
  5. 第一章、接口规范之web-api接口
  6. Appium|Locator Strategy ... is not supported for this session
  7. CDH5.16.1的Hbase1.2的G1参数配置
  8. Django模型层:单表操作,多表操作,常用(非常用)字段和参数,Django-model进阶
  9. How to export Overload functions from DLL?
  10. ubuntu系统---切换Py2.X与Py3.X版本