如何在 C# 中检查二叉树是否具有给定的路径总和?


HasPathsum 接受两个参数,一个为树节点,另一个为总和值,最初我们检查节点是否为 null,如果节点为 null,那么我们返回 false。如果节点不为 null,那么我们调用 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

更新于:2021 年 8 月 17 日

274 次浏览

开始你的职业

完成课程并获得认证

开始
广告
© . All rights reserved.