-
Notifications
You must be signed in to change notification settings - Fork 3
/
Search-in-BST
53 lines (41 loc) · 1003 Bytes
/
Search-in-BST
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
package com.tree.binarysearchtree;
public class Search {
public static void main(String[] args) {
TreeNode left = new TreeNode(4);
TreeNode right = new TreeNode(13);
TreeNode root = new TreeNode(9, left, right);
left.left = new TreeNode(2);
left.right = new TreeNode(7);
right.right = new TreeNode(17);
TreeNode res = search(7, root);
if (res != null)
System.out.println("Node found");
else
System.out.println("Node not found");
}
public static TreeNode search(int val, TreeNode root) {
if(root == null)
return null;
if(val == root.val)
return root;
if(val < root.val)
return search(val, root.left);
else
return search(val, root.right);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}