题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
解题思路:当用前序遍历的方式访问到某一结点时,把该结点添加到路径上,并累加该结点的值。如果该节点为叶结点并且路径中结点值的和刚好等于输入的整数,则当前的路径复核要求,把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到它的父结点。因此在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是从根结点到父结点的路径。
C#实现:public static void FindPath(BinaryTreeNode pRoot, int exceptedSum)
{
if (pRoot == null)
return;
List path = new List();
int currentSum = 0;
FindPath(pRoot, exceptedSum, path, ref currentSum);
}
private static void FindPath(BinaryTreeNode pRoot, int exceptedSum, List path, ref int currentSum)
{
currentSum += pRoot.value;
path.Add(pRoot.value);
// 如果是叶结点,并且路径上结点的和等于输入值
// 打印出这条路径
bool isLeaf = pRoot.left == null && pRoot.right == null;
if (currentSum == exceptedSum && isLeaf)
{
Console.WriteLine("A path is found: ");
foreach (int item in path)
Console.Write(item + "\t");
Console.WriteLine();
}
// 如果不是叶结点,则遍历它的子结点
if (pRoot.left != null)
FindPath(pRoot.left, exceptedSum, path, ref currentSum);
if (pRoot.right != null)
FindPath(pRoot.right, exceptedSum, path, ref currentSum);
// 在返回到父结点之前,在路径上删除当前结点,
// 并在currentSum中减去当前结点的值
currentSum -= pRoot.value;
path.RemoveAt(path.Count - 1);
}
Java实现:public static void findPath(BinaryTreeNode pRoot, int exceptedSum){
if(pRoot == null)
return;
List path = new LinkedList();
int currentSum = 0;
findPath(pRoot, exceptedSum, path, (Integer)currentSum);
}
private static void findPath(BinaryTreeNode pRoot, int exceptedSum, List path, Integer currentSum){
currentSum += pRoot.value;
path.add(pRoot.value);
// 如果是叶结点,并且路径上结点的和等于输入值
// 打印出这条路径
boolean isLeaf = pRoot.left == null && pRoot.right == null;
if(currentSum.intValue() == exceptedSum && isLeaf){
System.out.println("A path is found: ");
for(int item: path)
System.out.print(item + "\t");
System.out.println();
}
// 如果不是叶节点,则遍历它的子结点
if(pRoot.left != null)
findPath(pRoot.left, exceptedSum, path, currentSum);
if(pRoot.right != null)
findPath(pRoot.right, exceptedSum, path, currentSum);
// 在返回到父结点之前,在路径上删除当前结点,
// 并在currentSum中减去当前结点的值
currentSum -= pRoot.value;
path.remove(path.size()-1);
}
Python实现:@staticmethod
def findPath(pRoot, exceptedSum):
"""
二叉树中和为某一值的路径
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
:param pRoot:
:param exceptedSum:
:return:
"""
if pRoot == None:
return
path = []
currentSum = [0,]
BinaryTree.findPathChild(pRoot, exceptedSum, path, currentSum)
@staticmethod
def findPathChild(pRoot, exceptedSum, path, currentSum):
currentSum[0] += pRoot.value
path.append(pRoot.value)
# 如果是叶结点,并且路径上结点的和等于输入值
# 打印出这条路径
isLeaf = pRoot.left == None and pRoot.right == None
if currentSum[0] == exceptedSum and isLeaf:
print("A path is found:")
for item in path:
print(item, end=" ")
print()
# 如果不是叶节点,则遍历它的子结点
if pRoot.left != None:
BinaryTree.findPathChild(pRoot.left, exceptedSum, path, currentSum)
if pRoot.right != None:
BinaryTree.findPathChild(pRoot.right, exceptedSum, path, currentSum)
# 在返回到父结点之前,在路径上删除当前结点,
# 并在currentSum中减去当前结点的值
path.pop()
currentSum[0] -= pRoot.value