【面试题25】二叉树中和为某一值的路径

【题目描述】

输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶节点所经过的结点形成一条路径。

【解决方案】

用栈来存储路径,递归调用来遍历各个路径,如果符合条件,则进行打印。

考虑测试用例:

1. 二叉树中有一条或多条符合条件的路径;

2. 二叉树中没有符合条件的路径;

3. 指向二叉树结点的指针为null;

我的代码实现,仅供参考:

 1         public static void FindPath(BinaryTreeNode node, int targetSum, int currentSum, Stack<int> path)
 2         {
 3             if (node == null)
 4                 return;
 5 
 6             path.Push(node.Value);
 7             currentSum += node.Value;
 8 
 9             if (currentSum < targetSum)
10             {
11                 FindPath(node.Left, targetSum, currentSum, path);
12                 FindPath(node.Right, targetSum, currentSum, path);
13             }
14 
15             //到叶子结点正好和值为targeNum,则打印路径
16             if (currentSum == targetSum && node.Left == null && node.Right == null)
17             {
18                 PrintPath(path);
19             }
20 
21             path.Pop();
22         }
23 
24         public static void PrintPath(Stack<int> path)
25         {
26             List<int> list = path.ToList<int>();
27 
28             for (int i = list.Count - 1; i >= 0; i--)
29             {
30                 Console.WriteLine(list[i]);
31             }
32         }
原文地址:https://www.cnblogs.com/HuoAA/p/4807348.html