【笔试】42、二叉树中和为某一值的路径
2015-09-05 11:08
477 查看
/**************************************************************************************** *题目:二叉树中和为某一值的路径 * 输入一颗二叉树和一个整数,打印出二叉树中节点值和尾输入整数的所有路径。从树的根节点开始往下一直到 * 叶节点所经过的结点形成一条路径。 *时间:2015年9月5日10:53:32 *文件:PathInTree.java *作者:cutter_point ****************************************************************************************/ package bishi.Offer50.y2015.m09.d05; import java.util.*; import bishi.Offer50.y2015.m08.d26.*; public class PathInTree { public void findPath(BinaryTreeNode pRoot, int expectedSum) { if(pRoot == null) return; Vector<BinaryTreeNode> path = new Vector<BinaryTreeNode>(); int currentSum = 0; findPath(pRoot, expectedSum, path, currentSum); } /** * 用来寻找我们的路径,我们用递归,这样就可以自动返回到前一个根节点了 * @param pRoot 当前遍历到的节点 * @param expectedSum 我们统计的目标 * @param path 记录我们的路径 * @param currentSum 当前的和 */ private void findPath(BinaryTreeNode pRoot, int expectedSum, Vector<BinaryTreeNode> path, int currentSum) { //把当前的节点的值添加进去 currentSum += pRoot.m_nValue; path.add(pRoot); //是否就是我们的值,并且得是我们的叶节点 boolean isLeaf = pRoot.m_pLeft == null && pRoot.m_pRight == null; if(isLeaf && currentSum == expectedSum) { System.out.println("路径已经找到:"); for(int i = 0; i < path.size(); ++i) { System.out.print(path.get(i).m_nValue + "\t"); }//for System.out.println(); }//if //然后判断左右是否为空,如果还没有达到我们判定成功的值,那么继续递归下去 if(pRoot.m_pLeft != null) { findPath(pRoot.m_pLeft, expectedSum, path, currentSum); }//if if(pRoot.m_pRight != null) { findPath(pRoot.m_pRight, expectedSum, path, currentSum); }//if //这样如果当前节点递归结束,没有达到成功,返回上一个节点的时候,我们把路径也返回 currentSum -= pRoot.m_nValue; path.remove(pRoot); } public static void main(String[] args) { // 1 // / \ // 2 3 // / / \ // 4 5 6 // \ / // 7 8 // //我们的二叉树,用这个题的方法遍历的结果是 //1 2 3 4 5 6 7 8 // int preorder[] = {1,2,4,7,3,5,6,8}; int inorder[] = {4,7,2,1,5,3,8,6}; BinaryTree bt = new BinaryTree(); bt.construct(preorder, inorder); PathInTree pit = new PathInTree(); pit.findPath(bt.root, 9); } }
相关文章推荐
- POJ2155 Matrix(二维树状数组)
- 使用busybox制作微Linux系统
- Ubuntu12.04执行脚本程序的方法
- STM32通过USB实现Bootlader/IAP功能
- ActionScript 3.0 学习(十一) AS3 模拟接金币小游戏
- 综合案例:运算符的使用
- Linux异步I/O
- 值得推荐的C/C++框架和库 (真的很强大)
- ML_SVM的菜鸟实现
- 在配置Grunt的Task时通配符支持和动态生成文件名详解
- parseInt和valueOf
- 1.OA系统概述
- android 的service
- CSS基础知识
- 分层 分割(优秀)
- 动画演示10个超有趣的Linux命令
- C++ vector用法
- 中国移动手机阅读基地社会招聘笔试面试全过程
- c语言复杂数据类型
- 用Java语言编写一个金字塔程序