题目:输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点往下一直到叶子节点形成一条路径。

思路:很明显用前序遍历可以从根节点开始遍历到叶子节点,然后将遍历的节点添加到栈中进行保存路径。并且设置一个sum变量来记录节点值的和。通过对sum的操作来达到目的。

将抽象的问题具体化:

Java代码:

import java.util.Stack;

public class SumPath {
public class BinaryTreeNode{
int m_nValue;
BinaryTreeNode m_nLeft;
BinaryTreeNode m_nRight;
}
public BinaryTreeNode createBinaryTree(int[] pre,int start,int[] ord,int end,int length){
if(pre==null||ord==null||pre.length!=ord.length||length<=0)
return null;
int value=pre[start];
BinaryTreeNode root=new BinaryTreeNode();
root.m_nValue=value;
root.m_nLeft=root.m_nRight=null;
if(length==1){
if(pre[start]==ord[end])
return root;
else
throw new RuntimeException("inVaild put!");
}
//在中序遍历的序列中找到根节点
int i=0;
for(;i<length;i++){
if(ord[end-i]==value)
break;
}
if(i==length)
throw new RuntimeException("inVaild put!");
int left=length-i-1;
int right=i;
if(left>0)
root.m_nLeft=createBinaryTree(pre,start+1,ord,end-i-1,length-i-1);
if(right>0)
root.m_nRight=createBinaryTree(pre,start+length-i,ord,end,i);
return root;
}
public void sumPath(BinaryTreeNode root,int sum){
if(root==null)
return;
Stack<Integer> stack=new Stack<Integer>();
findPath(root,sum,stack);
}
public void findPath(BinaryTreeNode root, int sum, Stack<Integer> stack) {
if(root==null)
return;
//当遍历到叶子节点的时候,计算整个路径上的值是否为指定的值
if(root.m_nLeft==null&&root.m_nRight==null)
{
if(root.m_nValue==sum){
for(int i:stack)
System.out.print(i+",");
System.out.println(root.m_nValue);
}
}
stack.push(root.m_nValue);
//sum-root.m_nValue减去父节点的值,直到叶子几点,如果叶子节点等于剩下的值,那么就遍历成功。
if(root.m_nLeft!=null)
findPath(root.m_nLeft,sum-root.m_nValue,stack);
if(root.m_nRight!=null)
findPath(root.m_nRight,sum-root.m_nValue,stack);
stack.pop(); }
public static void main(String[] args){
int[] a={3,4,6,8,5,7,9};
int[] b={6,4,8,3,7,5,9};
SumPath sumPath=new SumPath();
BinaryTreeNode pHead=sumPath.createBinaryTree(a, 0, b, 6, a.length);
sumPath.sumPath(pHead, 15);
}
}

最新文章

  1. webpack-dev-server轻量级js高速打包、热部署服务器
  2. MySQL5.7中新增的JSON类型的使用方法
  3. JavaScripts 基础详细笔记整理
  4. 剑指Offer04 重建二叉树
  5. poj1160Post Office(DP)
  6. Django-RQ首页、文档和下载 - Django 和 RQ 集成 - 开源中国社区
  7. IOS 开发 【序】
  8. HDU_1016——素环问题DFS
  9. js 上下切换图片
  10. 数据库MySQL调优实战经验总结
  11. css 动画【转】
  12. redis持久化之AOF
  13. Php7有哪些新特性:
  14. 阿里云Redis公网连接的解决办法
  15. 实用的php购物车程序
  16. JS运动 - 无缝滚动和缓动动画
  17. Microsoft SQL Server 2012 管理 (2): 实例与数据库管理
  18. win8.1怎么安装iis
  19. SGU 206. Roads
  20. OFBiz:配置过程

热门文章

  1. ES6 随记(3.2)-- 正则的拓展 &amp; 数值的拓展
  2. Windows 10 安装 到SSD硬盘
  3. python 利用PIL库进行更改图片大小的操作
  4. tinyxml优化之一
  5. iOS设计模式探索
  6. 广度优先搜索 BFS算法
  7. MySQL explain 、explain extended用法
  8. spring半自动代理
  9. C语言,C#,Java,JavaScript之强类型与弱类型
  10. pxcook-高效易用的自动标注工具, 生成前端代码