标签:
本题来自《剑指offer》
路径为从根节点到叶节点一条路径,路径经过的各节点数值之和等于某一给定数值,则打印路径上的节点
1 //二叉树定义 2 class Btree { 3 int value; 4 Btree leftBtree; 5 Btree rightBtree; 6 } 7 private Stack<Integer> stack = new Stack<Integer>(); 8 public void FindPath(Btree node , int sum,int currSum){ 9 boolean isLeaf; 10 if(node == null) 11 return; 12 currSum += node.value; 13 stack.push(node.value); 14 isLeaf = node.leftBtree == null && node.rightBtree == null; 15 if(currSum == sum && isLeaf){ 16 System.out.println("Path:"); 17 for(int val : stack){ 18 System.out.println(val); 19 } 20 } 21 if(node.leftBtree != null) 22 FindPath(node.leftBtree, sum, currSum); 23 if(node.rightBtree != null) 24 FindPath(node.rightBtree, sum, currSum); 25 currSum -= node.value; 26 stack.pop(); 27 }
标签:
原文地址:http://www.cnblogs.com/music180/p/4720365.html