Repository navigation
Expand file tree
/
Copy pathproblem700.java
More file actions
117 lines (88 loc) · 2.95 KB
/
Copy pathproblem700.java
File metadata and controls
117 lines (88 loc) · 2.95 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//700. Search in a Binary Search Tree
import java.util.LinkedList;
import java.util.Queue;
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;
}
}
public class problem700 {
public static TreeNode searchBST(TreeNode root, int val) {
if(root==null)
{
return null;
}
if(root.val==val)
return root;
if(val>root.val && root.right!=null)
return searchBST(root.right, val);
return searchBST(root.left, val);
}
public static TreeNode buildTree(Integer[] arr) {
if (arr.length == 0 || arr[0] == null) return null;
TreeNode root = new TreeNode(arr[0]);
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < arr.length) {
TreeNode current = queue.poll();
// Left child
if (i < arr.length && arr[i] != null) {
current.left = new TreeNode(arr[i]);
queue.add(current.left);
}
i++;
// Right child
if (i < arr.length && arr[i] != null) {
current.right = new TreeNode(arr[i]);
queue.add(current.right);
}
i++;
}
return root;
}
public static void printTree(TreeNode root) {
if (root == null) {
System.out.println("The tree is empty.");
return;
}
// Initialize the queue and add the root node.
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
// Continue until there are no more nodes to process.
while (!queue.isEmpty()) {
// Number of nodes at the current level.
int levelSize = queue.size();
// Process all nodes on the current level.
for (int i = 0; i < levelSize; i++) {
TreeNode current = queue.poll();
System.out.print(current.val + " ");
// Enqueue left child if it exists.
if (current.left != null) {
queue.offer(current.left);
}
// Enqueue right child if it exists.
if (current.right != null) {
queue.offer(current.right);
}
}
// After processing the current level, move to a new line.
System.out.println();
}
}
public static void main(String[] args) {
Integer[] treeArray = {4,2,7,1,3};
// Construct the tree
TreeNode root = buildTree(treeArray);
printTree(searchBST(root, 2));
}
}