Java recursion solution


  • 0
    D
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return sumOfLeftLeaves(root, false);
        }
        
        private int sumOfLeftLeaves(TreeNode root, boolean leftchild) {
            if (root == null) {
                return 0;
            } 
            if (root.left == null && root.right == null) {
                return leftchild ? root.val : 0;
            }
            return (root.left == null ? 0 : sumOfLeftLeaves(root.left, true)) +
                   (root.right == null ? 0 : sumOfLeftLeaves(root.right, false));
        }
    }
    

Log in to reply
 

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