forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindPathFromRoot.java
71 lines (65 loc) · 1.25 KB
/
FindPathFromRoot.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/find-path-of-node-from-root.html
*/
package com.dsalgo;
import java.util.ArrayList;
import java.util.List;
public class FindPathFromRoot
{
public static void main(String[] args)
{
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
Node d = new Node(4);
Node e = new Node(5);
Node f = new Node(6);
Node g = new Node(7);
Node h = new Node(8);
a.left = b;
a.right = c;
b.left = d;
c.left = e;
c.right = f;
f.left = g;
f.right = h;
List<Node> path = findPath(a, d);
for (Node node : path)
System.out.println(node.value);
}
private static List<Node> findPath(Node root, Node node)
{
if (root == null)
return null;
List<Node> path = new ArrayList<Node>();
if (root == node)
{
path.add(root);
return path;
}
List<Node> leftPath = findPath(root.left, node);
List<Node> rightPath = findPath(root.right, node);
if (leftPath != null)
{
leftPath.add(0, root);
return leftPath;
}
if (rightPath != null)
{
rightPath.add(0, root);
return rightPath;
}
return null;
}
static class Node
{
Node left;
Node right;
int value;
public Node(int value)
{
this.value = value;
}
}
}