101.[Tree][Easy] Symmetric Tree

Problem

https://leetcode.com/problems/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.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

// solution 1: recursive
// check if left subtree is a "mirror" of right subtree
// Time O(n)
// Space O(h)
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null || root.left == null && root.right == null) {
            return true;
        }
        if (root.left == null || root.right == null) {
            return false;
        }
        return isSymmetricHelper(root.left, root.right);
    }
    
    public boolean isSymmetricHelper(TreeNode p, TreeNode q) {
        if(p == null && q == null) {
            return true;
        } 
        if(p == null || q == null) {
            return false;
        }
        if(p.val != q.val) {
            return false;
        }
        
        return isSymmetricHelper(p.left, q.right) && isSymmetricHelper(p.right, q.left);
    }
}

// solution 2: iterative
// use 2 stacks to hold left subtree and right subtree in reverse order, compare when pop()
// Time O(n)
// Space O(n)
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null || root.left == null && root.right == null) {
            return true;
        }
        if(root.left == null || root.right == null) {
            return false;
        }
        
        Stack left = new Stack<>();
        left.push(root.left);
        Stack right = new Stack<>();
        right.push(root.right);
        
        while(!left.empty() || !right.empty()) {
            TreeNode currLeft = left.pop();
            TreeNode currRight = right.pop();
            
            if (currLeft == null && currRight == null) { continue;}
            if (currLeft == null || currRight == null) { return false;}
            
            if (currLeft.val != currRight.val) {
                return false;
            }
            left.push(currLeft.left);
            left.push(currLeft.right);
            right.push(currRight.right);
            right.push(currRight.left);
        }
        
        return left.empty() && right.empty();
        
    }
}

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