Java Iterative Solution: concise and easy


  • 0

    Besides the root, every time we push two nodes into the stack.
    Of course we need to check if the two nodes matches when we push them.
    Then we pop two nodes out of the stack and start to process their four children.

    public boolean isSymmetric(TreeNode root) {
            if(root==null) return true;
            Stack<TreeNode> stack = new Stack<>();
            if(!pushToStack(root.left, root.right, stack))
                return false;
            
            while(!stack.isEmpty()){
                TreeNode left = stack.pop();
                TreeNode right = stack.pop();
                if(!pushToStack(left.left, right.right, stack))
                    return false;
                if(!pushToStack(left.right, right.left, stack))
                    return false;
            }
            
            return true;
        }
        
        public boolean pushToStack(TreeNode n1, TreeNode n2, Stack<TreeNode> stack){
            if(n1==null || n2==null) return n1==n2;
            if(n1.val!=n2.val) return false;
            stack.push(n1);
            stack.push(n2);
            return true;
        }
    
    

Log in to reply
 

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