1. 程式人生 > >輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑

ger roo pop void set null push ava 所有

題目:

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。
從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

解答:

 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 }

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑