-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathInsert-in-BST
61 lines (50 loc) · 1.13 KB
/
Insert-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
52
53
54
55
56
57
58
59
60
package com.tree.binarysearchtree;
public class Insert {
public static void main(String[] args) {
TreeNode left = new TreeNode(5);
TreeNode right = new TreeNode(9);
TreeNode root = new TreeNode(8, left, right);
left.left = new TreeNode(2);
left.right = new TreeNode(6);
int val = 7;
System.out.println("Inorder Traversal before Inserting "+val);
inorder(root);
insert(val, root);
System.out.println("\nInorder Traversal after Inserting "+ val);
inorder(root);
}
public static TreeNode insert(int val, TreeNode root) {
if(root == null) {
root = new TreeNode(val);
}
else {
if(val < root.val)
root.left = insert(val, root.left);
else
root.right = insert(val, root.right);
}
return root;
}
public static void inorder(TreeNode root) {
if(root == null)
return;
inorder(root.left);
System.out.print(root.val + " ");
inorder(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;
}
}