c#二叉树中路径和的计算方法

avatar
作者
筋斗云
阅读量:0

以下是用C#实现二叉树中路径和的计算方法:

using System;  public class TreeNode {     public int val;     public TreeNode left;     public TreeNode right;     public TreeNode(int value = 0, TreeNode leftChild = null, TreeNode rightChild = null)     {         val = value;         left = leftChild;         right = rightChild;     } }  public class BinaryTree {     public int PathSum(TreeNode root, int sum)     {         if (root == null)         {             return 0;         }          return PathSumFrom(root, sum) + PathSum(root.left, sum) + PathSum(root.right, sum);     }      private int PathSumFrom(TreeNode node, int sum)     {         if (node == null)         {             return 0;         }          int count = 0;         if (node.val == sum)         {             count++;         }          count += PathSumFrom(node.left, sum - node.val);         count += PathSumFrom(node.right, sum - node.val);          return count;     } }  class Program {     static void Main()     {         TreeNode root = new TreeNode(10);         root.left = new TreeNode(5);         root.right = new TreeNode(-3);         root.left.left = new TreeNode(3);         root.left.right = new TreeNode(2);         root.right.right = new TreeNode(11);         root.left.left.left = new TreeNode(3);         root.left.left.right = new TreeNode(-2);         root.left.right.right = new TreeNode(1);          BinaryTree tree = new BinaryTree();         int sum = 8;         int result = tree.PathSum(root, sum);          Console.WriteLine("Number of paths with sum " + sum + ": " + result);     } } 

在上面的代码中,我们定义了一个TreeNode类来表示二叉树中的节点,以及一个BinaryTree类来计算二叉树中路径和等于给定值的路径数量。在BinaryTree类中,我们使用递归的方法来遍历二叉树,并计算路径和等于给定值的路径数量。在Main方法中,我们创建了一个二叉树,并计算路径和等于8的路径数量。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!