Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
Solution in Java 1: 递归方法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null||root.left==null&&root.right==null) return true;
else if(root.left==null||root.right==null || root.left.val!=root.right.val) return false;
return valid(root.left, root.right);
}
public boolean valid(TreeNode left, TreeNode right){
boolean check = left.val==right.val;
if(left.left==null&&right.right==null) check = check&&true;
else if(left.left!=null&& right.right!=null) check= check&& valid(left.left, right.right);
else return false;
if(left.right==null&&right.left==null) check = check&&true;
else if(left.right!=null&&right.left!=null) check = check&& valid(left.right, right.left);
else return false;
return check;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null||root.left==null&&root.right==null) return true;
else if(root.left==null||root.right==null || root.left.val!=root.right.val) return false;
Stack<TreeNode> preOrder = new Stack<TreeNode>();
Stack<TreeNode> postOrder = new Stack<TreeNode>();
TreeNode lroot = root.left, rroot = root.right;
while(lroot!=null||rroot!=null|| !preOrder.empty() ||!postOrder.empty()){
while(lroot!=null || rroot!=null){ //at least one of lroot and rroot is not null then enter the loop
if(rroot==null || lroot==null ||lroot.val!=rroot.val) return false;
//neither rroot nor lroot is null, otherwise return false
preOrder.push(lroot);
postOrder.push(rroot);
lroot = lroot.left;
rroot = rroot.right;
}
if(preOrder.size()!=postOrder.size()) return false;
if(!preOrder.empty()){
lroot = preOrder.pop();
rroot = postOrder.pop();
lroot = lroot.right;
rroot=rroot.left;
}
}
return true;
}
}从左右根结点出发,设置两种相反的遍历方式:中左右和中右左,遍历中每个点都相同则结果为true。

本文介绍了一种检查二叉树是否为中心对称的方法,提供了递归与非递归两种解决方案。递归方法通过比较左右子树实现,非递归方法采用两个栈分别进行前序遍历和后序遍历。
5万+

被折叠的 条评论
为什么被折叠?



