LeetCode - Easy - 700. Search in a Binary Search Tree

刺骨的言语ヽ痛彻心扉 2022-10-06 02:52 249阅读 0赞

Topic

  • Tree

Description

https://leetcode.com/problems/search-in-a-binary-search-tree/

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

Example 1:

ffba7471511eeb6c265220cd86424e2d.png

  1. Input: root = [4,2,7,1,3], val = 2
  2. Output: [2,1,3]

Example 2:

5bf615955b29f3dbd9226cbebd3678ca.png

  1. Input: root = [4,2,7,1,3], val = 5
  2. Output: []

Constraints:

  • The number of nodes in the tree is in the range [ 1 , 5000 ] [1, 5000] [1,5000].
  • 1 < = N o d e . v a l < = 1 0 7 1 <= Node.val <= 10^7 1<=Node.val<=107
  • root is a binary search tree.
  • 1 < = v a l < = 1 0 7 1 <= val <= 10^7 1<=val<=107

Analysis

方法一:递归法

方法二:迭代法

Submission

  1. import com.lun.util.BinaryTree.TreeNode;
  2. public class SearchInABinarySearchTree {
  3. //方法一:递归法
  4. public TreeNode searchBST(TreeNode root, int val) {
  5. if(root == null) return null;
  6. if(val < root.val)
  7. return searchBST(root.left, val);
  8. else if(root.val < val)
  9. return searchBST(root.right, val);
  10. else
  11. return root;
  12. }
  13. //方法二:迭代法
  14. public TreeNode searchBST2(TreeNode root, int val) {
  15. TreeNode p = root;
  16. while(p != null) {
  17. if(val < p.val) {
  18. p = p.left;
  19. }else if(val > p.val){
  20. p = p.right;
  21. }else {
  22. return p;
  23. }
  24. }
  25. return null;
  26. }
  27. }

Test

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. import com.lun.util.BinaryTree;
  4. import com.lun.util.BinaryTree.TreeNode;
  5. public class SearchInABinarySearchTreeTest {
  6. @Test
  7. public void test() {
  8. SearchInABinarySearchTree obj = new SearchInABinarySearchTree();
  9. TreeNode root = BinaryTree.integers2BinaryTree(4,2,7,1,3);
  10. TreeNode expected = BinaryTree.integers2BinaryTree(2,1,3);
  11. assertTrue(BinaryTree.equals(obj.searchBST(root, 2), expected));
  12. assertNull(obj.searchBST(root, 5));
  13. }
  14. @Test
  15. public void test2() {
  16. SearchInABinarySearchTree obj = new SearchInABinarySearchTree();
  17. TreeNode root = BinaryTree.integers2BinaryTree(4,2,7,1,3);
  18. TreeNode expected = BinaryTree.integers2BinaryTree(2,1,3);
  19. assertTrue(BinaryTree.equals(obj.searchBST2(root, 2), expected));
  20. assertNull(obj.searchBST2(root, 5));
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,249人围观)

还没有评论,来说两句吧...

相关阅读