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
- Cracking the coding interview--Q4.8
- Cracking the coding interview--Q4.8
- Cracking the coding interview--Q4
- Cracking the coding interview--Q4.1
- Cracking the coding interview--Q4.2
- Cracking the coding interview--Q4.3
- Cracking the coding interview--Q4.4
- Cracking the coding interview--Q4.5
- Cracking the coding interview--Q4.6
- Cracking the coding interview--Q4.7
- Cracking the coding interview--Q4.1
- Cracking the coding interview--Q4.2
- Cracking the coding interview--Q4.3
- Cracking the coding interview--Q4.4
- Cracking the coding interview--Q4.5
- Cracking the coding interview--Q4.6
- Cracking the coding interview--Q4.7
- Cracking the Coding Interview
- cocos2dx快捷创建项目脚本
- Android APP如何防止二次打包
- Python查询天气小程序
- UML之协作图
- Cocos2d-x Scene生命周期 pushScene和replaceScene
- Cracking the coding interview--Q4.8
- NYOJ 107 A Famous ICPC Team
- Cocos2dx-游戏开发中不同的坐标系,cocos2dx锚点
- 超简单的数码相框制作
- “舍友勾搭上我爸还怀孕了!
- linux lib 动态库
- 设计模式之----------------桥接模式
- 双卡双待手机[海信]挂断来电和指定卡去电实现
- 题目1146:Flipping Pancake