Skip to content

Commit f7850e7

Browse files
Create Binary Search Trees:Find Path in BST
1 parent f9987d3 commit f7850e7

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Binary Search Trees:Find Path in BST

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import java.util.ArrayList;
2+
3+
public class Solution {
4+
5+
/* Binary Tree Node class
6+
*
7+
* class BinaryTreeNode<T> {
8+
T data;
9+
BinaryTreeNode<T> left;
10+
BinaryTreeNode<T> right;
11+
12+
public BinaryTreeNode(T data) {
13+
this.data = data;
14+
}
15+
}
16+
*/
17+
18+
public static ArrayList<Integer> findPath(BinaryTreeNode<Integer> root, int data){
19+
/* Your class should be named Solution
20+
* Don't write main().
21+
* Don't read input, it is passed as function argument.
22+
* Return output and don't print it.
23+
* Taking input and printing output is handled automatically.
24+
*/
25+
if(root==null)
26+
return null;
27+
if(root.data==data)
28+
{
29+
ArrayList<Integer> output=new ArrayList<>();
30+
output.add(root.data);
31+
return output;
32+
}
33+
if(data<root.data)
34+
{
35+
ArrayList<Integer> output=findPath(root.left,data);
36+
37+
if(output!=null)
38+
{
39+
output.add(root.data);
40+
return output;
41+
}
42+
}
43+
ArrayList<Integer> output2;
44+
if(data>root.data)
45+
{
46+
output2=findPath(root.right,data);
47+
48+
if(output2!=null){
49+
output2.add(root.data);
50+
return output2;}}
51+
52+
53+
return null;
54+
55+
56+
57+
}
58+
}

0 commit comments

Comments
 (0)