题目:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
解答:
1 import java.util.*; 2 3 public class Solution { 4 public static void main(String[] args) { 5 BinaryTreeNode root=new BinaryTreeNode(10); 6 BinaryTreeNode node1=new BinaryTreeNode(5); 7 BinaryTreeNode node2=new BinaryTreeNode(4); 8 BinaryTreeNode node3=new BinaryTreeNode(7); 9 BinaryTreeNode node4=new BinaryTreeNode(12); 10 root.setLchildNode(node1);root.setRchildNode(node4); 11 node1.setLchildNode(node2);node1.setRchildNode(node3); 12 findPath(root,22); 13 } 14 15 private static void findPath(BinaryTreeNode root, int i) { 16 if(root == null) { 17 return; 18 } 19 20 Stack<Integer> stack = new Stack<Integer>(); 21 int currentSum = 0; 22 findPath(root, i, stack, currentSum); 23 } 24 25 private static void findPath(BinaryTreeNode root, int i, Stack<Integer> stack, int currentSum) { 26 currentSum = currentSum + root.getData(); 27 stack.push(root.getData()); 28 29 if(root.getLchildNode() == null && root.getRchildNode() == null) { 30 if(currentSum == i) { 31 System.out.println("find path"); 32 for(int path:stack) { 33 System.out.println(path + " "); 34 } 35 } 36 } 37 38 if(root.getLchildNode() != null) { 39 findPath(root.getLchildNode(), i, stack, currentSum); 40 } 41 42 if(root.getRchildNode() != null) { 43 findPath(root.getRchildNode(), i, stack, currentSum); 44 } 45 46 stack.pop(); 47 } 48 }