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
Note:
Bonus points if you could solve it both recursively and iteratively.
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return judge(root,root);
}
private boolean judge(TreeNode root1,TreeNode root2){
if(root1==null&&root2==null){
return true;
}
if(root1==null||root2==null){
return false;
}
return root1.val==root2.val&&
judge(root1.left,root2.right)&&
judge(root1.right,root2.left);
}
}
时间:O(n)
空间:O(n)
时隔多年还是没做对T-T,绕不开的二叉树
我一开始的思路是对左右子节点进行判断,后来发现根本不是那样的
是要对左子树和右子树进行判断,这样的话判断方法就需要两个节点(两个子树),在他们都为空或者左右子树递归返回true时,代表他是镜像树,递归可能会满一点,不知道是不是上下文环境切换造成的
非递归思路就是层序遍历,使用先进先出队列queue,先放两个root,再放一左一右,一右一左
判断方法同上
网友评论