- Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathConstruct-Binary-Search-Tree-From-Preorder-Traversal.scala
52 lines (47 loc) · 1.74 KB
/
Construct-Binary-Search-Tree-From-Preorder-Traversal.scala
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
classTreeNode(_value: Int=0, _left: TreeNode=null, _right: TreeNode=null) {
varvalue:Int= _value
varleft:TreeNode= _left
varright:TreeNode= _right
}
//DFS solution
objectSolution {
defbstFromPreorder(preorder: Array[Int]):TreeNode= {
varparentList= scala.collection.mutable.Seq.empty[TreeNode]
valroot=newTreeNode(preorder(0))
defbstFromPreorderWithIndex(index: Int, parent: TreeNode):Unit= {
if (index != preorder.length) {
if (parent.value > preorder(index)) {
parent.left =newTreeNode(preorder(index))
parentList = parentList.+:(parent)
bstFromPreorderWithIndex(index +1, parent.left)
} else {
if (parentList.isEmpty || preorder(index) < parentList.head.value) {
parent.right =newTreeNode(preorder(index))
bstFromPreorderWithIndex(index +1, parent.right)
} else {
valnewParent= parentList.head
parentList = parentList.tail
bstFromPreorderWithIndex(index, newParent)
}
}
}
}
bstFromPreorderWithIndex(1, root)
root
}
}
//recursive (not tailRec) solution
objectSolution2 {
defbstFromPreorder(preorder: Array[Int]):TreeNode=
bstFromPreorderWithRange(0, preorder.length -1, preorder)
defbstFromPreorderWithRange(start: Int, end: Int, preorder: Array[Int]):TreeNode= {
if (start > end) null
else {
valnode=newTreeNode(preorder(start))
valleftIndexBound= (start to end).find(i => preorder(i) > preorder(start)).getOrElse(end +1) -1
node.left = bstFromPreorderWithRange(start +1, leftIndexBound, preorder)
node.right = bstFromPreorderWithRange(leftIndexBound +1, end, preorder)
node
}
}
}