Skip to content

Commit 6ecbf13

Browse files
committed
Update 700. 二叉搜索树中的搜索 迭代法
1 parent 32e04ea commit 6ecbf13

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

algorithms/search-in-a-binary-search-tree.js

+16
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* @return {TreeNode}
1313
*/
1414
var searchBST = function (root, val) {
15+
// 递归
1516
if (!root) {
1617
return null;
1718
}
@@ -22,4 +23,19 @@ var searchBST = function (root, val) {
2223
} else {
2324
return root;
2425
}
26+
27+
// 迭代
28+
// return helper(root, val);
2529
};
30+
function helper(root, val) {
31+
while (root) {
32+
if (val > root.val) {
33+
root = root.right;
34+
} else if (val < root.val) {
35+
root = root.left;
36+
} else {
37+
return root;
38+
}
39+
}
40+
return null;
41+
}

0 commit comments

Comments
 (0)