Skip to content

Commit b32c74a

Browse files
committed
Balanced Binary Tree
1 parent 40ae952 commit b32c74a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Diff for: Balanced Binary Tree.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*Given a binary tree, determine if it is height-balanced.
2+
3+
For this problem, a height-balanced binary tree is defined as:
4+
5+
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
6+
7+
Example 1:
8+
9+
Given the following tree [3,9,20,null,null,15,7]:
10+
11+
3
12+
/ \
13+
9 20
14+
/ \
15+
15 7
16+
Return true.
17+
18+
Example 2:
19+
20+
Given the following tree [1,2,2,3,3,null,null,4,4]:
21+
22+
1
23+
/ \
24+
2 2
25+
/ \
26+
3 3
27+
/ \
28+
4 4
29+
Return false.*/
30+
31+
/**
32+
* Definition for a binary tree node.
33+
* function TreeNode(val) {
34+
* this.val = val;
35+
* this.left = this.right = null;
36+
* }
37+
*/
38+
/**
39+
* @param {TreeNode} root
40+
* @return {boolean}
41+
*/
42+
var isBalanced = function(root) {
43+
if(root == null)
44+
return true
45+
var diff = depth(root.left) - depth(root.right)
46+
if(Math.abs(diff) > 1)
47+
return false
48+
return isBalanced(root.left) && isBalanced(root.right)
49+
};
50+
51+
var depth = function(node){
52+
if(node == null)
53+
return 0
54+
return 1 + Math.max(depth(node.left), depth(node.right))
55+
}

0 commit comments

Comments
 (0)