Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
64 lines (52 loc) · 1.39 KB

File metadata and controls

64 lines (52 loc) · 1.39 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* <!--
* This program is distributed under
* the terms of the MIT license.
* Please see the LICENSE file for details.
* -->
*/
/*
* Given a sorted array, write an algorithm to create a binary tree
* with minimal height.
* Use the Node structure in 007.js
*/
/*____________________________________________________________________________*/
function addToTree(ar, start, end) {
if (end < start) {
return null;
}
var mid = Math.floor((start+end)/2);
var n = new Node(null, null, ar[mid]);
n.left = addToTree(ar, start, mid - 1);
n.right = addToTree(ar, mid + 1, end);
return n;
}
/**
* @class {public} Node
*
* A typical binary tree node.
*
* @param {Node} left - the left node.
* @param {Node} right - the right node.
* @param {Integer} value - the value of this node.
*/
function Node(left, right, value) {
this.left = left;
this.right = right;
this.value = value;
}
/*____________________________________________________________________________*/
var ar = [1, 2, 3, 4, 5, 6, 7, 8];
console.log( addToTree(ar, 0, ar.length - 1) );
/*
Output: ($ /usr/bin/node 010.js)
{ left:
{ left: { left: null, right: null, value: 1 },
right: { left: null, right: null, value: 3 },
value: 2 },
right:
{ left: { left: null, right: null, value: 5 },
right: { left: null, right: [Object], value: 7 },
value: 6 },
value: 4 }
*/
Morty Proxy This is a proxified and sanitized view of the page, visit original site.