Leetcode题目101.对称二叉树(简单)
2024-09-02 23:16:03
题目描述:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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;
}
}
}
最新文章
- static变量引起的问题,List数据覆盖
- 从 github 执行 git clone 一个大的项目时提示 error: RPC failed
- 【转】C++ 单例模式
- dell 交换机 双链路冗余
- Android样式的编写格式
- supervisor的集中化管理搭建
- 用python脚本获取运行环境中的module 列表
- Nginx, HTTPS的配置
- 【模板】倍增+Floyd
- Matlab-11:Gausssidel迭代法工具箱
- centos记录uptime,tomcat日志切割,远程拷贝日志脚本
- PowerDesigner 教程
- LInux内核分析--使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用
- Java保存文本文件
- 如何防止网页被植入广告,内容被监控-HTTPS
- 使用T-SQL导入多个文件数据到SQL Server中
- Thrift Expected protocol id ffffff82 but got 0
- SqlServer2012数据导入
- 赋予Winform程序管理员访问权限
- linux下构建SVN
热门文章
- pthread 编程基础
- 如何成为优秀的技术Leader
- VC文件扩展名
- IPhone中H5页面用on绑定click无效的解决方法
- 第一章、接口规范之web-api接口
- Appium|Locator Strategy ... is not supported for this session
- CDH5.16.1的Hbase1.2的G1参数配置
- Django模型层:单表操作,多表操作,常用(非常用)字段和参数,Django-model进阶
- How to export Overload functions from DLL?
- ubuntu系统---切换Py2.X与Py3.X版本