如何在 C# 中检查二叉树是否具有给定的路径和?
csharpserver side programmingprogramming更新于 2025/4/18 5:52:17
HasPathsum 有 2 个参数,一个是树节点,另一个是和值,首先我们检查节点是否为空,如果节点为空,则返回 false。如果节点不为空,则我们调用 HasPathSum 递归方法,在每个递归步骤中,我们不断从节点值中减去和值。如果和的值达到 0,则我们得出结论,给定的树具有等于和的路径并返回 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

