Modified Pre-Order traversal, 13ms, Simple and Clean


  • 0
    E

    The solution is base on pre-order tree traversal. We only push right children to the stack. If we pop the node from stack, that means it is a right child.

     public int sumOfLeftLeaves(TreeNode root) {
            int sum = 0; 
            boolean isLeftNode = false;
            Stack<TreeNode> s = new Stack();
            s.push(root);
            while(!s.isEmpty()){
                if(root!=null){
                    if(root.right!=null){
                        s.push(root.right);
                    }else if(root.left==null && isLeftNode){
                        sum+=root.val;
                    }
                    root=root.left;
                    isLeftNode=true;
                }else{
                    root=s.pop();
                    isLeftNode=false;
                }
            }
            return sum;
        }
    
    

Log in to reply
 

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