101. Symmetric Tree

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.

Solution1: [post-order]Recursive check

思路:
Time Complexity: O(N) Space Complexity: O(logN) 递归缓存

Solution2: Iterative check, pre-inorder by stack,

思路: 判断 元素值一样 && 结构一样(若空都空,若有都有)
Time Complexity: O(N) Space Complexity: O(logN)

Solution1 Code:

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

Solution2 Code:

class Solution {
    private Stack stack;
    
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        
        TreeNode left, right;
        stack = new Stack();
        // push root.left, and root.right
        if(pushStackIfValid(root.left, root.right) == false) return false;
        
        while(!stack.isEmpty()) {
            // if(stack.size() % 2 != 0) return false;
            right = stack.pop();
            left = stack.pop();
            if(left.val != right.val) return false;
            
            // push left.left, and right.right, when valid (Both them are not null)
            if(pushStackIfValid(left.left, right.right) == false) return false;
            
            // push left.right and right.left, when valid (Both them are not null)
            if(pushStackIfValid(left.right, right.left) == false) return false;
        }
        return true;
    }
    
    private boolean pushStackIfValid(TreeNode node1, TreeNode node2) {
        // Valid: All two are not null. if not valid, return -1;
        if(node1 != null && node2 != null) {
            stack.push(node1);
            stack.push(node2);
            return true;
        }
        //else if(node1 != null && node2 == null || node1 == null && node2 != null)
        else if(node1 == null ^ node2 == null)
            return false;
        
        else return true;
    }
    
    private boolean pushStackIfValid2(TreeNode node1, TreeNode node2) {
        // Valid: All two are not null. if not valid, return -1;
        if(node1 != null) {
            if(node2 == null) return false;
            stack.push(node1);
            stack.push(node2);
        }
        else if(node2 != null) return false;
        return true;
        
    }
}

你可能感兴趣的:(101. Symmetric Tree)