Concise iterator solution


  • 0
    F
    public boolean isSymmetric(TreeNode root) {
            if (root == null) return true;
            Deque<TreeNode> stack1 = new LinkedList<>(), stack2 = new LinkedList<>();
            TreeNode p = root.left, q = root.right;
            while (true) {
                if (p == null || q == null) {
                    if (p != q) return false;
                    if (stack1.isEmpty() && stack2.isEmpty()) break;
                    p = stack1.pop();
                    q = stack2.pop();
                    p = p.right;
                    q = q.left;
                    continue;
                }
                if (p.val != q.val) return false;
                stack1.push(p);
                stack2.push(q);
                p = p.left;
                q = q.right;
            }
            
            return true;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.