java - 递归程序中类变量到方法参数的转换

标签 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);
            }
        }
    }

最佳答案

总是根据自身的更简单版本来定义递归问题。

调用函数 LL。

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

归纳案例:给定 LL( node.left ) 和 LL( node.right ) -> LL( node ) ≡ 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 );
}

关于java - 递归程序中类变量到方法参数的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124614/

相关文章:

java - 为什么使用 SimpleDateFormat '23:00 PM' 解析 ("hh:mm aa") 返回上午 11 点?

algorithm - 从这个集合中选择两个区间的快速算法

c# - 使用 C# 循环使用 Wpf tabitem 控件?

java - 递归随机数生成器

java - 如何在Java中获取文件的 "details"

java - 冲洗物体的正确位置

java - addproperty() 函数中不同类型的属性?

algorithm - 为什么 DFA 等同于延迟输入 DFA

javascript - 给定一组 6 位数字,找出所有可能的 "non-duplicate"组合

java - 递归搜索链表