two types of java recursive solution


  • 0
    F

    first one:

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

    second one:

        private int result = 0;
    
        public int sumOfLeftLeaves2(TreeNode root) {
            dfs2(root, false);
            return result;
        }
    
        private void dfs2(TreeNode root, boolean isLeft) {
            if (root != null) {
                if (isLeft && root.left == root.right) {
                    result += root.val;
                } else {
                    dfs2(root.left, true);
                    dfs2(root.right, false);
                }
            }
        }
    

Log in to reply
 

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