LeetCode 101. Symmetric Tree 对称二叉树(Java)

题目:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Note:
Bonus points if you could solve it both recursively and iteratively.
LeetCode 101. Symmetric Tree 对称二叉树(Java)_第1张图片

解答:

解法一:递归

两棵子树对称的条件:根节点相等,左子树的左子树和右子树的右子树对称,左子树的右子树和右子树的左子树对称

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null){
            return true;
        }
        return isSymmetric(root.left,root.right);
    }
    private boolean isSymmetric(TreeNode left,TreeNode right){
        if(left==null&&right==null){
            return true;
        }else if(left==null||right==null){
            return false;
        }
        return (left.val==right.val)&&(isSymmetric(left.left,right.right))&&(isSymmetric(left.right,right.left));
    }
}

解法二:非递归

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Stack<TreeNode> stack=new Stack<>();
        stack.push(root);
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode s1=stack.pop();
            TreeNode s2=stack.pop();
            if(s1==null&&s2==null){
                continue;
            }else if(s1==null||s2==null){
                return false;
            }else if(s1.val!=s2.val){
                return false;
            }
            stack.push(s1.left);
            stack.push(s2.right);
            stack.push(s1.right);
            stack.push(s2.left);
        }
        return true;        
    }
}

你可能感兴趣的:(LeetCode)