/// <summary> /// 找出二叉树中和为某一值的所有路径 /// </summary> class BinarySearch { public static void Do() { int[] tree = { 10,5,8,4,7,1}; int currentSum=0; PostOrderSerach(tree, 0, new Stack<int>(), ref currentSum, 19); } public static void PostOrderSerach(int[] tree, int cur, Stack<int> pathStack, ref int currentSum, int expectedSum) { pathStack.Push(tree[cur]); //不会重复遍历已经访问过的节点 currentSum += tree[cur]; if (currentSum == expectedSum) { DisplayPath(pathStack, "路径"); } //递归遍历左子树 int left = (cur + 1) * 2 - 1; if (left < tree.Length) { PostOrderSerach(tree, left, pathStack, ref currentSum, expectedSum); } //递归遍历右子树 int right = (cur + 1) * 2; if (right < tree.Length) { PostOrderSerach(tree, right, pathStack, ref currentSum, expectedSum); } //在后续遍历的位置退栈 int tmp= pathStack.Pop(); currentSum -= tmp; } public static void DisplayPath(Stack<int> path,string title) { Console.Write(title + ":"); foreach (var item in path.Reverse<int>()) { Console.Write(item + ","); } Console.WriteLine(); } }