简体   繁体   English

二叉树级别总和-

[英]Binary Tree Level Sum -

A basic Java sample: Given a binary tree and an integer which is the depth of the target level. 一个基本的Java示例:给定一个二叉树和一个整数,它是目标级别的深度。 And calculate the sum of the nodes in the target level. 并计算目标级别中节点的总和。

I am adding the value in the functions to the left and right node. 我将函数中的值添加到左侧和右侧节点。 Why this solution doesn't work in this case, Can anyone help explain? 为什么这种解决方案在这种情况下不起作用,有人可以帮忙解释一下吗?

Also, when the travese function got returned, is it returning to the parent root or more like break; 同样,当travese函数返回时,它返回父根还是更像break; in for loop and the flow got stopped? 在循环中,流程停止了吗?

private int sum;

public int levelSum(TreeNode root, int level) {
    sum = 0;
    traverse(root, 1, level, 0);
    return sum;
}

public void traverse(TreeNode root, int depth, int level, int sum) {
    if(root == null) {
        return;
    }

    if(depth == level) {
        return;
    }

    if(root.left != null) {
        traverse(root.left, depth + 1, level, sum + root.left.val);
    }

    if(root.right != null) {
        traverse(root.right, depth + 1, level, sum + root.right.val);
    }
}

First of all, you didn't return the result of summation. 首先,您没有返回求和的结果。 You will have to return it. 您将不得不退还它。

Then, since you wrote "in the target level", I guess you will have to sum up nodes only in the target level, not nodes before the level. 然后,由于您写的是“在目标级别”,因此我想您只需要总结目标级别中的节点,而不是该级别之前的节点。

Try this: 尝试这个:

public int levelSum(TreeNode root, int level) {
    return traverse(root, 1, level);

}

public void traverse(TreeNode root, int depth, int level){
    int sum = 0;

    if(root == null || depth > level){
        return 0;
    }

    if (depth == level) sum += root.val;

    if(root.left != null) {
        sum += traverse(root.left, depth + 1, level);
    }

    if(root.right != null) {
        sum += traverse(root.right, depth + 1, level);
    }

    return sum;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM