Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. //Method 1:
  2.  
  3. public Node getClosestBSTNode( Node root, int k ){
  4. if( root == null ){
  5. return null;
  6. }
  7. return getClosestBSTNode( root, k, root.data() - k );
  8. }
  9.  
  10. public Node getClosestBSTNode( Node node, int k, int parentDiff ){
  11. if( parentDiff == 0 ){
  12. return node;
  13. }
  14. Node closestLeftBSTNode = getClosestBSTNode( node.getLeft(), k, node.getData() - k );
  15. Node closestRightBSTNode = getClosestBSTNode( node.getRight(), k, node.getData() - k );
  16.  
  17. if( parentDiff < ( closestLeftBSTNode.getData() - k) || parentDiff < ( closestRightBSTNode.getData() - k) ){
  18. return node;
  19. }
  20. if( Math.abs (closestLeftBSTNode.getData() - k) <= Math.abs( closestRightBSTNode.getData() - k ) ){
  21. return closestLeftBSTNode;
  22. } else{
  23. return closestRightBSTNode;
  24. }
  25. }
  26.  
  27. // Method 2:
  28.  
  29. public Node getClosestBSTNode( Node root ){
  30. return getClosestBSTNode( root, k );
  31. }
  32.  
  33. public Node getClosestBSTNode( Node node, int k, Node closestNode ){
  34. if ( node == null ){
  35. return null;
  36. }
  37.  
  38. int currData = node.data
  39. if( currData == k ){
  40. return node;
  41. } else if( currData < k ){
  42. int diff = Math.abs( currData - k );
  43. int closestDiff = Math.abs( closestNode.getData() - k );
  44. if( diff < closestDiff ){
  45. return getClosestBSTNode( node.getRight(), k, node );
  46. } else{
  47. return getClosestBSTNode( node.getRight(), k, closestNode );
  48. }
  49. } else if ( currData > k ){
  50. int diff = Math.abs( currData - k );
  51. int closestDiff = Math.abs( closestNode.getData() - k );
  52. if( diff < closestDiff ){
  53. return getClosestBSTNode( node.getLeft(), k, node );
  54. } else{
  55. return getClosestBSTNode( node.getLeft(), k, closestNode );
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement