-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructBinaryTreeFromPreorderAndInorderTraversal.js
More file actions
72 lines (62 loc) · 2.48 KB
/
constructBinaryTreeFromPreorderAndInorderTraversal.js
File metadata and controls
72 lines (62 loc) · 2.48 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
/*
* Given preorder and inorder traversal of a tree, construct the binary tree.
*
* Note:
* You may assume that duplicates do not exist in the tree.
*
* For example, given
*
* preorder = [3,9,20,15,7]
* inorder = [9,3,15,20,7]
* Return the following binary tree:
*
* 3
* / \
* 9 20
* / \
* 15 7
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
// explanation of binary tree traversal methods: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/trees.html
// let's use example of
// * preorder = [3,9,20,15,7]
// * inorder = [9,3,15,20,7]
var buildTree = function(preorder, inorder) {
let preOrderStart = 0,
preOrderEnd = preorder.length - 1,
inOrderStart = 0,
inOrderEnd = inorder.length - 1;
function traverse(preOrderStart, preOrderEnd, inOrderStart, inOrderEnd){
if (preOrderStart > preOrderEnd || inOrderStart > inOrderEnd ) { return null; }
// since preorder tree's first node is root, find that value, which is 3 in this case
let rootValue = preorder[preOrderStart];
// find where 3 is in inorder array, which is index=1.
// we'll use this index to split this array into 2 halves right/left
// now inorder can be split into [(9) | 3 | (15, 20, 7)] where 3 is the root
let indexOfRootValueInOrder = inorder.indexOf(rootValue); // this is 1
// now looking at the tree, number of values on left side is 1 - 0 = 1
let numberOfValuesOnLeftSide = indexOfRootValueInOrder - inOrderStart;
let rootNode = new TreeNode(rootValue);
// do the same traversal logic for the left side of the tree.
// for preorder array this will start at 1 and end at 0 + 1 = 1
// for inorder array this will start at 0 and end at 1 - 1 = 0
rootNode.left = traverse(preOrderStart + 1, preOrderStart + numberOfValuesOnLeftSide,
inOrderStart, indexOfRootValueInOrder-1);
// do the same traversal logic for the right side of the tree
rootNode.right = traverse(preOrderStart + numberOfValuesOnLeftSide + 1, preOrderEnd,
indexOfRootValueInOrder + 1, inOrderEnd);
return rootNode;
}
return traverse(preOrderStart, preOrderEnd, inOrderStart, inOrderEnd);
};