Given a binary tree, check whether it is amirror 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 44 3
But the following [1,2,2,null,3,null,3] isnot:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it bothrecursively and iteratively.
翻译:给定一个二叉树,检查它是否是自己的镜像(即围绕其中心对称)。希望能够给出递归和非递归两种做法
分析:对于递归来说,若根节点为空,返回true,否则递归调用它的左右孩子。比较简单,也比较好理解
对于非递归来说,利用栈,若左右孩子不空,然后每次都将左右孩子入栈进行比较,思路比较清楚,代码也比较好些,具体两种方法的代码如下:
public class Solution {
/*public boolean isSymmetric(TreeNode root) {
if(root==null) return true;
if(isTrue(root.left,root.right))
return true;
else
return false;
}
public boolean isTrue(TreeNode left, TreeNode right){
if(left==null||right==null)
return left==right;
if(left.val!=right.val)
return false;
return isTrue(left.left, right.right) && isTrue(left.right,right.left);
}*/
public boolean isSymmetric(TreeNode root) {
TreeNode left,right;
Stack<TreeNode> stack =new Stack();
if(root==null) return true;
if(root.left!=null){
if(root.right==null) return false;
stack.push(root.left);
stack.push(root.right);
}else if(root.right!=null){
return false;
}
while(!stack.empty()){
if(stack.size()%2!=0) returnfalse;
right=stack.pop();
left=stack.pop();
if(right.val!=left.val)return false;
if(left.left!=null){
if(right.right==null)return false;
stack.push(left.left);
stack.push(right.right);
}else if(right.right!=null){
return false;
}
if(left.right!=null){
if(right.left==null)return false;
stack.push(left.right);
stack.push(right.left);
}elseif(right.left!=null){
return false;
}
}
return true;
}
}