子树结构

Symmetric Tree

  • naive recursive solution, create helper method isSymmetric(TreeNode left, TreeNode right)

  • iterative solution

    • use stack and push left and right to the stack firstly

    • then create a while loop to pop from stack

    • check whether stk.size() % 2 == 0

    • check whether both left and right are null or equal

    • stk.push(left.left);

    • stk.push(right.right);

    • stk.push(left.right);

    • stk.push(right.left);

class Solution {
    
    //iterative, use stack, every time push left and right node to stack
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return false;
        // return isSymmetric(root.left, root.right);
        Stack<TreeNode> stk = new Stack<>();
        stk.push(root.left);
        stk.push(root.right);
        while (!stk.isEmpty()) {
            if (stk.size() % 2 != 0) return false;
            TreeNode right = stk.pop();
            TreeNode left = stk.pop();
            if (right == null && left == null) continue;
            if (right == null || left == null || right.val != left.val) return false;
            stk.push(left.left);
            stk.push(right.right);
            stk.push(left.right);
            stk.push(right.left);
        }
        return true;
    }
    
    //recursive
    private boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null || left.val != right.val) return false;
        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }
}

Last updated

Was this helpful?