问题:请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如:二叉树 [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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { boolean n=true; public boolean isSymmetric(TreeNode root) { if(root==null||(root.left==null&&root.right==null)) return true; if(root.left==null||root.right==null) return false; hui(root.left,root.right); return this.n; } void hui(TreeNode root,TreeNode tree){ if(this.n==false) return; if(root==null&&tree==null) return; if(root==null||tree==null){ this.n=false; return; } if(root.val!=tree.val){ this.n=false; return; } hui(root.left,tree.right); hui(tree.left,root.right); } }
|
解析:这个问题采用递归的方法,从最上方的根节点向下依次判断,将左节点看做root,右节点看成tree,每次root左移时,tree右移,保证root和tree一直处于对称的位置。判断root和tree是否相等,若不相等,则证明该二叉树是不对称的。如果tree和root有一项为空而另一项不为空,则该二叉树也是不对称的。
题目链接:对称的二叉树 - 对称的二叉树 - 力扣(LeetCode)