-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathheightOfSpecialBinaryTree.js
More file actions
46 lines (41 loc) · 1.06 KB
/
heightOfSpecialBinaryTree.js
File metadata and controls
46 lines (41 loc) · 1.06 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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const isLeafNode = (node) => {
if (node.left && node.left.right && node.left.right.val === node.val) {
return true;
}
if (node.right && node.right.left && node.right.left.val === node.val) {
return true;
}
return false;
}
var heightOfTree = function (root) {
const arr = [];
arr.push([root, 0]);
let curr, currDepth;
let result = 0;
while (arr.length > 0) {
[curr, currDepth] = arr.pop();
if (isLeafNode(curr)) {
result = Math.max(result, currDepth);
} else {
if (curr.left) {
arr.push([curr.left, currDepth + 1]);
}
if (curr.right) {
arr.push([curr.right, currDepth + 1]);
}
}
}
return result;
};