Last active
June 19, 2020 17:36
-
-
Save voxqhuy/9ba00828e3c6c96dec23d8457ec70d81 to your computer and use it in GitHub Desktop.
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
// 700. Search in a Binary Search Tree | |
// link: https://leetcode.com/problems/search-in-a-binary-search-tree/ | |
// Solution: recursive | |
// Time O(n), Space O(n) | |
public TreeNode searchBST(TreeNode root, int val) { | |
if (root == null) { return null; } | |
if (root.val == val) { return root; } | |
TreeNode node = root.val < val | |
? searchBST(root.right, val) | |
: searchBST(root.left, val); | |
return node; | |
} | |
// Solution 2: iterative | |
// Time O(n), Space O(n) | |
public TreeNode searchBST(TreeNode root, int val) { | |
Stack<TreeNode> stack = new Stack<TreeNode>(); | |
stack.push(root); | |
while (!stack.empty()) { | |
TreeNode node = stack.pop(); | |
if (node == null) { continue; } | |
if (node.val == val) { return node; } | |
if (node.val < val) { | |
stack.push(node.right); | |
} else { | |
stack.push(node.left); | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment