Depth First Search Very Easy to Understand!


  • 3
    F

    Depth First Search keeping track of if it is a left child or not. Major thing is we are Checking if Node is a leaf Node and if the Node is a left child in-between left root and right root recursive calls (Basically a modified In Order Traversal). Very Simple.

    class Solution {
        static boolean leftChild=false, rightChild = false;
        int sum=0;
        public int sumOfLeftLeaves(TreeNode root) {
                if(root ==null) return sum;
            
                if(root.left!=null){
                    rightChild=false;
                    leftChild=true;
                    sumOfLeftLeaves(root.left);
                }
    
                if((root.left ==null && root.right==null) && leftChild && !rightChild) sum+= root.val;
    
                if(root.right!=null){
                    rightChild=true;
                    leftChild=false;
                    sumOfLeftLeaves(root.right);
                }
            return sum;
        }
    }
    

  • 0
    M

    nice and clean... very simple and helpful


Log in to reply
 

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