Skip to content

Commit 187882d

Browse files
committed
leetcode solution
1 parent 53e3c30 commit 187882d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

validate-binary-search-tree.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {boolean}
11+
*/
12+
var isValidBST = function (root) {
13+
if (root === null) {
14+
return true;
15+
}
16+
17+
// inorder sort
18+
var ret = [];
19+
var stack = [root];
20+
var cur = root;
21+
22+
while (stack.length > 0) {
23+
if (cur && cur.left) {
24+
cur = cur.left;
25+
stack.push(cur);
26+
} else {
27+
if (stack.length > 0) {
28+
var temp = stack.pop();
29+
ret.push(temp.val);
30+
cur = temp.right;
31+
if (cur) {
32+
stack.push(cur);
33+
}
34+
}
35+
}
36+
}
37+
38+
// check whether the result is in order sequence
39+
for (var i = 0; i < ret.length; i++) {
40+
if (i > 0 && ret[i] <= ret[i - 1]) {
41+
return false;
42+
}
43+
}
44+
return true;
45+
};

0 commit comments

Comments
 (0)