-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSortedArrayToBalancedBST.java
99 lines (84 loc) · 2.96 KB
/
SortedArrayToBalancedBST.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
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
/*https://practice.geeksforgeeks.org/problems/array-to-bst4443/1*/
//GFG version without creating a tree and using iterative preorder travresal technique
class Data
{
int start;
int mid;
int end;
Data(int s, int e)
{
start = s;
end = e;
mid = (s+e)/2;
}
}
class Solution
{
public int[] sortedArrayToBST(int[] nums)
{
int[] result = new int[nums.length];
int index = 0;
//create a stack and push the range of the array
Stack<Data> stack = new Stack<Data>();
stack.push(new Data(0,nums.length-1));
//till the stack becomes empty
while (!stack.isEmpty())
{
//pop the current data from stack
Data curr = stack.pop();
//store the corresponding element in the result
result[index++] = nums[curr.mid];
//if the right subtree has more than one nodes then push the right subtree range
if (curr.mid != curr.end) stack.push(new Data(curr.mid+1,curr.end));
//if the left subtree has more than one nodes then push the left subtree range
if (curr.start != curr.mid) stack.push(new Data(curr.start,curr.mid-1));
}
return result;
}
}
/*https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/*/
//Leetcode version by creating a tree and using same iterative preorder technique
class Data
{
int start;
int mid;
int end;
TreeNode parent;
Data(int s, int e, TreeNode node)
{
start = s;
end = e;
mid = (s+e)/2;
parent = node;
}
}
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode root = null;
//create a stack and push the range of the array
Stack<Data> stack = new Stack<Data>();
stack.push(new Data(0,nums.length-1,null));
//till the stack becomes empty
while (!stack.isEmpty())
{
//pop the current data from stack
Data curr = stack.pop();
//create a new node for the data
TreeNode currNode = new TreeNode(nums[curr.mid]);
//attach it to the proper place
//if root is null then attach to root
if (root == null) root = currNode;
else
{
//if value is less than parent attach as left child else as right child
if (currNode.val < curr.parent.val) curr.parent.left = currNode;
else curr.parent.right = currNode;
}
//if the right subtree has more than one nodes then push the right subtree range along with parent
if (curr.mid != curr.end) stack.push(new Data(curr.mid+1,curr.end,currNode));
//if the left subtree has more than one nodes then push the left subtree range along with parent
if (curr.start != curr.mid) stack.push(new Data(curr.start,curr.mid-1,currNode));
}
return root;
}
}