您的位置:首页 > 其它

leetcode--Symmetric Tree

2017-08-08 10:06 330 查看
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.

分类:二叉树

题意:判断一棵二叉树是否对称

解法1:递归。判断是否左右子树是否相等。具体方法是如果都为空,则返回真,否则判断是否其中一个为空,或者值不相等,则返回假。否则最后递归判断左右子树。

[java] view
plain copy

/** 

 * 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) return true;  

        return solve(root.left, root.right);  

    }  

      

    public boolean solve(TreeNode left,TreeNode right){  

        if(left==null&&right==null) return true;//  

        if((left!=null && right==null) || (left==null && right!=null)   

                || (left.val!=right.val)) return false;       

        return solve(left.left, right.right)&&solve(left.right, right.left);                  

    }  

}  

解法2:使用栈代替递归。左子树顺序入栈,右子树反向入栈。

[java] view
plain copy

/** 

 * 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) return true;  

        Stack<TreeNode> leftStack = new Stack<TreeNode>();  

        Stack<TreeNode> rightStack = new Stack<TreeNode>();  

        leftStack.add(root.left);  

        rightStack.add(root.right);  

        while(leftStack.size()>0&&rightStack.size()>0){  

            TreeNode left = leftStack.pop();  

            TreeNode right = rightStack.pop();  

            if(left!=null&&right==null) return false;  

            if(left==null&&right!=null) return false;  

            if(left!=null&&right!=null){  

                if(left.val!=right.val) return false;  

                //左右子树入栈方向相反  

                leftStack.add(left.left);  

                leftStack.add(left.right);  

                rightStack.add(right.right);  

                rightStack.add(right.left);  

            }  

        }  

        return true;  

    }  

}  



原文链接http://blog.csdn.net/crazy__chen/article/details/46377605
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: