Skip to content

Commit ba64648

Browse files
committed
Add two solution about Tree.
1 parent c5a42f9 commit ba64648

File tree

3 files changed

+82
-3
lines changed

3 files changed

+82
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//
2+
// Copyright (c) 2015 by liril.net. All Rights Reserved.
3+
//
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* function TreeNode(val) {
8+
* this.val = val;
9+
* this.left = this.right = null;
10+
* }
11+
*/
12+
13+
/**
14+
* @param {TreeNode} root
15+
* @return {number}
16+
*/
17+
var maxDepth = function(root) {
18+
var stackNode = Array(), stackHeight = Array();
19+
var height = 0, max = 0;
20+
while (root || stackNode.length) {
21+
while (root) {
22+
height++;
23+
stackNode.push(root);
24+
stackHeight.push(height);
25+
root = root.left;
26+
}
27+
root = stackNode.pop();
28+
height = stackHeight.pop();
29+
if (!root.left && !root.right) {
30+
if (!max) max = height;
31+
max = Math.max(max, height);
32+
}
33+
root = root.right;
34+
}
35+
return max;
36+
};
37+
38+
console.log(maxDepth([1]));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//
2+
// Copyright (c) 2015 by liril.net. All Rights Reserved.
3+
//
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* function TreeNode(val) {
8+
* this.val = val;
9+
* this.left = this.right = null;
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {number}
15+
*/
16+
var minDepth = function(root) {
17+
var stackNode = Array(), stackHeight = Array();
18+
var height = 0, min = 0;
19+
while (root || stackNode.length) {
20+
while (root) {
21+
height++;
22+
stackNode.push(root);
23+
stackHeight.push(height);
24+
root = root.left;
25+
}
26+
root = stackNode.pop();
27+
height = stackHeight.pop();
28+
if (!root.left && !root.right) {
29+
if (!min) min = height;
30+
min = Math.min(min, height);
31+
}
32+
root = root.right;
33+
}
34+
return min;
35+
};

README.md

+9-3
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,17 @@ Tree
4141
| | |-- Missing-Number.js
4242
| | |-- Number-of-1-Bits.js
4343
| | `-- Power-of-Two.js
44-
| `-- Math
45-
| `-- Reverse-Integer.js
44+
| |-- Math
45+
| | `-- Reverse-Integer.js
46+
| |-- String
47+
| | |-- Add-Binary.js
48+
| | `-- Basic-Calculator-II.js
49+
| `-- Tree
50+
| |-- Maximum-Depth-of-Binary-Tree.js
51+
| `-- Minimum-Depth-of-Binary-Tree.js
4652
|-- README.md
4753
`-- package.json
4854
49-
4 directories, 26 files
55+
6 directories, 30 files
5056
5157
```

0 commit comments

Comments
 (0)