Advertisement
1988coder

270. Closest Binary Search Tree Value

Nov 26th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 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. N = Total number of nodes in the BST
  17. */
  18. class Solution {
  19.     public int closestValue(TreeNode root, double target) throws NullPointerException {
  20.         if (root == null) {
  21.             throw new NullPointerException("Input Tree root is null");
  22.         }
  23.        
  24.         int closest = root.val;
  25.         while (root != null) {
  26.             if (Math.abs(root.val - target) < Math.abs(closest - target)) {
  27.                 closest = root.val;
  28.             }
  29.             if (target == root.val) {
  30.                 break;
  31.             }
  32.             root = target < root.val ? root.left : root.right;
  33.         }
  34.        
  35.         return closest;
  36.     }
  37. }
  38.  
  39.  
  40. /*
  41. Recursive Solution
  42.  
  43. Time Complexity: O(N) - If the tree is skewed it will visit all nodes.
  44. Space Complexity: O(H)
  45. N = Total number of nodes in the BST
  46. H = Height of the binary Tree. (Recursion Stack)
  47. */
  48. class Solution {
  49.     public int closestValue(TreeNode root, double target) throws NullPointerException {
  50.         if (root == null) {
  51.             throw new NullPointerException("Input Tree root is null");
  52.         }
  53.        
  54.         int[] closest = new int[1];
  55.         closest[0] = root.val;
  56.         closestValueHelper(closest, root, target);
  57.         return closest[0];
  58.     }
  59.    
  60.     public void closestValueHelper(int[] closest, TreeNode node, double target) {
  61.         if (node == null) {
  62.             return;
  63.         }
  64.         if (target == node.val) {
  65.             closest[0] = node.val;
  66.             return;
  67.         }
  68.         if (Math.abs(node.val - target) < Math.abs(closest[0] - target)) {
  69.                 closest[0] = node.val;
  70.         }
  71.         if (target < node.val) {
  72.             closestValueHelper(closest, node.left, target);
  73.         } else {
  74.             closestValueHelper(closest, node.right, target);
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement