在递归程序中将类变量转换为方法参数

时间:2017-03-30 17:27:56

标签: java algorithm recursion

我已经解决了leetcode问题,用这段代码在树中找到Sum of left leaves。我知道使用类可变量作为递归中的临时变量是一种不好的做法,有些如何将临时结果作为方法参数传递。在这种情况下,我想避免使用类变量sum并使用附加参数创建辅助方法sumOfLeftLeaves(TreeNode root,TreeNode parent,int sum)。请建议我如何修改方法。我尝试了不同的方法来做到这一点,但是对于返回值感到震惊。

//Find sum of all left nodes in a binary tree.    
public class Solution {
        //Class variable to capture sum
        int sum = 0;
        public int sumOfLeftLeaves(TreeNode root) {
             sumOfLeftLeaves(root,null);
             return sum;
        }

        public void sumOfLeftLeaves(TreeNode root,TreeNode parent){
            if(root != null){
                sumOfLeftLeaves(root.left,root);
                //If the node is a leaft node and it is left node to the parent
                if(root.left == null && root.right == null && (parent != null && parent.left == root)){
                    sum += root.val;
                }
                sumOfLeftLeaves(root.right,root);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

始终根据更简单的版本定义递归问题。

调用LL函数。

基本情况:LL(空)≡0,LL(左叶节点)≡node.val,LL(右叶节点)≡0

归纳案例:给定LL(node.left)和LL(node.right) - > LL(节点)≡LL(node.left)+ LL(node.right)

public int sumOfLeftLeavesAux( TreeNode node, boolean flgIsLeftChild ) {
    // base case: empty tree
    if ( node == null )
        return 0;
    // base case: leaf node
    if ( node.left == null && node.right == null )
        return flgIsLeftChild ? node.val : 0;
    // inductive case
    return sumOfLeftLeavesAux( node.left, true ) + sumOfLeftLeavesAux( node.right, false );
}