Advertisement
1988coder

700. Search in a Binary Search Tree

Nov 25th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10.  
  11. /*
  12. Iterative Solution
  13.  
  14. Time Complexity: O(N) - If the tree is skewed it will visit all nodes.
  15. Space Complexity: O(1)
  16.  
  17. N = Number of nodes in the binary search tree.
  18. */
  19. class Solution {
  20.     public TreeNode searchBST(TreeNode root, int val) {
  21. //         if (root == null) {
  22. //             return null;
  23. //         }
  24.        
  25.         TreeNode cur = root;
  26.         while (cur != null) {
  27.             if (cur.val == val) {
  28.                 return cur;
  29.             }
  30.             cur = cur.val < val ? cur.right : cur.left;
  31.         }
  32.         return cur;
  33.     }
  34. }
  35.  
  36. /*
  37. Recusrive Solution
  38.  
  39. Time Complexity: O(N) - If the tree is skewed it will visit all nodes.
  40. Space Complexity: O(H)
  41.  
  42. N = Number of nodes in the binary search tree.
  43. H = Height of tree. (Recursion Stack)
  44. */
  45. class Solution {
  46.     public TreeNode searchBST(TreeNode root, int val) {
  47.         if (root == null) {
  48.             return null;
  49.         }
  50.         if (root.val == val) {
  51.             return root;
  52.         }
  53.        
  54.         return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement