Cracking the coding interview--Q4.8

来源:互联网 发布:2017淘宝黑科技 编辑:程序博客网 时间:2024/05/20 11:19

题目

原文:

You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.

译文:

给一个每个结点都包含一个值的二叉树,设计一个算法打印所有满足这个条件的路径:路径上结点的值加起来等于给定的一个值。注意:这些路径不一定从根节点开始。

解答

结点中包含指向父亲结点的指针,那么,只需要去遍历这棵二叉树, 然后从每个结点开始,不断地去累加上它父亲结点的值直到父亲结点为空(这个具有唯一性, 因为每个结点都只有一个父亲结点。也正因为这个唯一性, 可以不另外开额外的空间来保存路径),如果等于给定的值sum,则打印输出。

代码如下:

import java.util.Stack;class Q4_8{public static void findSum(TreeNode head,int sum){if(head==null) return;TreeNode tnode=head;int tmp=0;for(int i=1;tnode!=null;i++){tmp+=tnode.value;if(tmp==sum)print(head,i);tnode=tnode.parent;}findSum(head.lchild,sum);findSum(head.rchild,sum);}private static void print(TreeNode tnode,int level){Stack<Integer> s=new Stack<Integer>();for(int i=0;i<level;i++){s.push(tnode.value);tnode=tnode.parent;}while(s.size()>0){System.out.print(s.pop()+" ");}}public static void main(String[] args){int[] arr={5,1,3,8,6,10};TreeNode root=TreeNode.createBinaryTree(arr);findSum(root,23);}}

---EOF---


0 0
原创粉丝点击