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
105 lines (93 loc) · 2.07 KB

File metadata and controls

105 lines (93 loc) · 2.07 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
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
100
101
102
103
104
105
/*
* <!--
* This program is distributed under
* the terms of the MIT license.
* Please see the LICENSE file for details.
* -->
*/
/*
* Implement a function to check if a tree is balanced.
* A balance tree is a tree with no two leaf nodes differ in distance from the
* root by more than one.
* Use the Node structure in 007.js
*/
/*____________________________________________________________________________*/
/**
* @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;
}
/*
* Sample tree structure.
*/
var root = new Node(
new Node(
new Node(null, null, 28),
new Node(null, null, 79),
62
),
new Node(
new Node(
new Node(null, null, 121),
null,
130),
new Node(null, null, 190),
141
),
110
);
/**
* @function {public static} getMaxDepth
*
* Gets the maximum depth of a subtree.
*
* @param {Node} root - the node to start.
*
* @return the max depth of the subtree.
*/
function getMaxDepth(root) {
if (!root) {
return 0;
}
return 1 + Math.max(getMaxDepth(root.left), getMaxDepth(root.right));
}
/**
* @function {public static} getMinDepth
*
* Gets the minimum depth of a subtree.
*
* @param {Node} root - the node to start.
*
* @return the min depth of the subtree.
*/
function getMinDepth(root) {
if (!root) {
return 0;
}
return 1 + Math.min(getMinDepth(root.left), getMinDepth(root.right));
}
/**
* @function {public static} isBalanced
*
* Checks whether the tree is balanced.
*
* @param {Node} root - the root node of the tree.
*/
function isBalanced(root) {
return getMaxDepth(root) - getMinDepth(root) <= 1;
}
/*____________________________________________________________________________*/
console.log( isBalanced(root) );
/*
Output: ($ /usr/bin/node 009.js)
true
*/
Morty Proxy This is a proxified and sanitized view of the page, visit original site.