如何在 C# 中检查二叉树是否具有给定的路径和?
HasPathsum有2个参数,一个是树节点,另一个是和值,最初我们检查节点是否为空,如果节点为空则返回false。如果节点不为空,那么我们调用HasPathSum递归方法,在每个递归步骤中,我们不断从节点值中减去总和值。如果sum的值达到0,那么我们得出结论,给定的树具有等于sum的路径并返回true。
示例
public class TreesPgm{
public class Node{
public int Value;
public Node LeftChild;
public Node RightChild;
public Node(int value){
this.Value = value;
}
public override String ToString(){
return "Node=" + Value;
}
}
public bool HasPathSum(Node node, int sum){
if (root == null){
return false;
}
return helperHasPathSum(node, sum);
}
private bool helperHasPathSum(Node root, int sum){
if (root == null){
return false;
}
sum -= root.Value;
if (root.LeftChild == null &&root.RightChild== null && sum == 0){
return true;
}
return helperHasPathSum(root.LeftChild, sum) || helperHasPathSum(root.RightChild, sum);
}
}输入
5
2 6
1 3
7输出结果True
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短