Created
April 16, 2024 15:40
-
-
Save yevmoroz/51a2eb1ef102e8f0f89d56a023e5969a to your computer and use it in GitHub Desktop.
leetcode binary tree search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
* @param {number} val | |
* @return {TreeNode} | |
*/ | |
function searchBST(root, val) { | |
let cur = root | |
while (cur) { | |
if (cur.val == val) { | |
return cur; | |
} else if (cur.val > val) { | |
cur = cur.left; | |
} else { | |
cur = cur.right; | |
} | |
} | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment