import java.util.Stack;
public class Test25_FindPath
{
public static void main(String[] args)
{
//创建二叉树
TreeNode root1 = new TreeNode(10);
TreeNode node2 = new TreeNode(5);
TreeNode node3 = new TreeNode(12);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(7);
root1.left = node2;
root1.right = node3;
node2.left = node4;
node2.right = node5;
int sum = 22;
//查找和为sum的路径
findPath(root1, sum);
}
private static void findPath(TreeNode root1, int sum)
{
if(root1 == null){
return;
}
int currentSum = 0;
Stack<Integer> stack = new Stack<Integer>();
findPath(root1, sum, currentSum, stack);
}
private static void findPath(TreeNode root1, int sum, int currentSum,
Stack<Integer> stack)
{
//路径是并行的 currentSum之间不会相互影响
currentSum += root1.value;
stack.push(root1.value);
//如果为叶子节点 且路径的和为sum 则打印这条路径
if(root1.left == null && root1.right == null)
{
if(currentSum == sum)
{
for (Integer pathPoint : stack)
{
System.out.print(pathPoint+" ");
}
System.out.print("\n");
}
}
//如果不是叶子节点 则遍历它的子节点
if(root1.left != null)
{
findPath(root1.left, sum, currentSum, stack);
}
if(root1.right != null)
{
findPath(root1.right, sum, currentSum, stack);
}
//在返回父节点之前 在路径上删除当前节点 (为了方便打印路径)
stack.pop();
}
}
二叉树中和为某一值得路径
最新推荐文章于 2021-07-23 08:40:15 发布