Java recursive solution using DFS


  • 0
    B
    
    public class Solution {
        int res = 0;
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) {
                return 0;
            }
            TreeNode node = root;
            dfs(root);
            return res;
        }
        private TreeNode dfs(TreeNode node) {
            if(node == null) {
                return null;
            }
            TreeNode left = dfs(node.left);
            TreeNode right = dfs(node.right);
            //here, it is a leaf
            if (left != null && left.left == null && left.right == null) {
                res = res + left.val;  
            }
            return node;
        }
    }
    

Log in to reply
 

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