JAVA solution using DFS


  • 0
    Z

    It is easy to understand how this code works, but I'm confused why this method is slower than Recursive or even BFS?

    class Solution {
        int sum = 0;
        public int sumOfLeftLeaves(TreeNode root) {
            sum = 0;
            dfs(root, false);
            return sum;
        }
        public void dfs(TreeNode root, boolean isLeft){
            if(root.left == null && root.right == null && isLeft) {
                sum += root.val;
                return;
            }
            if(root.left != null) dfs(root.left, true);
            if(root.right != null) dfs(root.right, false);
        }
    }
    

Log in to reply
 

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