Easy Java with explanation


  • 0
    V

    A quick solution to track from which side the current node is at, if it is left, then add it to the sum or else ignore it.
    Here is the code:

    int toRet;
        public int sumOfLeftLeaves(TreeNode root) 
        {
            toRet = 0;
            dfs(root, -1);
            return toRet;
        }
        void dfs(TreeNode root, int dir)
        {
            if(root == null)
                return;
            if(dir == 0 && root.left == null && root.right == null)
            {
                toRet += root.val;
                return;
            }
            dfs(root.left, 0);
            dfs(root.right, 1);
        }

Log in to reply
 

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