forked from marsprince/SwordForOffer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindPath.java
More file actions
44 lines (42 loc) · 910 Bytes
/
FindPath.java
File metadata and controls
44 lines (42 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package Problem25;
import java.util.Stack;
public class FindPath {
/*
* 输入一个二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径
*/
public void findPath(BinaryTreeNode root,int k)
{
if(root==null)
return ;
Stack<Integer> stack=new Stack<Integer>();
findPath(root,k,stack);
}
private void findPath(BinaryTreeNode root,int k,Stack<Integer> path)
{
if(root==null)
return ;
if(root.leftNode==null && root.rightNode==null)
{
if(root.data==k)
{
System.out.println("路径开始");
for(int i:path)
System.out.println(i);
System.out.println(root.data);
}//打印栈
}
else
{
path.push(root.data);
findPath(root.leftNode,k-root.data,path);
findPath(root.rightNode,k-root.data,path);
path.pop();
}
}
}
class BinaryTreeNode
{
int data;
BinaryTreeNode leftNode;
BinaryTreeNode rightNode;
}