Symmetric Tree
来源:互联网 发布:xshell连接linux 编辑:程序博客网 时间:2024/06/06 12:27
题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
做这道题,最好的解法我觉得应该是递归求解。开始我想的是先层序遍历,然后判断回文,发现不好使。后来收大神启发,用了递归,效率杠杠的。话不多说,上代码:
public boolean isSymmetric(TreeNode root) { return root == null || helpSmmetric(root.left, root.right); } public boolean helpSmmetric(TreeNode left, TreeNode right) { //递归结束条件节点为空的情况,为空说明至少一个分支已经到低了,后面的也不需要在比较 if (left == null || right == null) { return left == right; } //递归结束条件节点不为空的情况,只要不等直接返回false,后面不需要比较 if (left.val != right.val) return false; //递归调用可确保每次对比的节点都是对称的节点 return helpSmmetric(left.left, right.right) && helpSmmetric(left.right, right.left); }
感觉递归好好用,我开始没用递归,写了好长的代码才勉强实现功能,然而递归核心步骤才几行。
阅读全文
0 0
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- (C)顺序表实现集合运算
- 简单题两道(三分求极值)
- (CodeForces
- 剑指offer_数组---把数组排成最小的数
- Python学习(十三)——pandas函数库2
- Symmetric Tree
- 千寻穗C语言学习笔记 8.25 8.26(伪)
- 关于puppet脚本的一些笔记
- KMP算法
- Listener(监听器)
- 作用域public,protected,private的区别?以及不写时的区别?
- 一张图理清SpringMVC工作原理
- HDFS对象存储:Ozone的块异步删除服务
- AWS