Java Easy Solution 10ms runtime


  • 0
    R
    public int sumOfLeftLeaves(TreeNode root) {
            int sum = 0;
            int result = sumOfLeftLeavesUtil(root, false, sum);
            return result;
        }
        
        public int sumOfLeftLeavesUtil(TreeNode root, boolean leftFlag, int sum){
            if(root == null){
                return 0;
            }
            
            if((root.left == null && root.right == null) &&(leftFlag)){
                sum+=root.val;
            }
            
            if(root.left != null){
                leftFlag = true;
                sum = sumOfLeftLeavesUtil(root.left,leftFlag, sum);
            }
            
            if(root.right != null){
                leftFlag = false;
                sum = sumOfLeftLeavesUtil(root.right,leftFlag, sum);
            }
            
            return sum;
        }

Log in to reply
 

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