Simple Java Recursive Solution


  • 0
    W
    public int sumOfLeftLeaves(TreeNode root) {
        	if(root == null) {
        		return 0;
        	}
            int[] sum = new int[1];
            return traverse(root, sum, false);
        }
    
    	private int traverse(TreeNode root, int[] sum, boolean flag) {
    		if(root.left == null && root.right == null) {
    			if(flag)
    				sum[0] += root.val;
    			return sum[0]; 
    		}
    		if(root.left != null) {
    			traverse(root.left, sum, true);
    		}
    		if(root.right != null) {
    			traverse(root.right, sum, false);
    		}
    		return sum[0];
    	}
    

    True or False denotes whether the node is left node or right node


Log in to reply
 

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