Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Method 1:
- public Node getClosestBSTNode( Node root, int k ){
- if( root == null ){
- return null;
- }
- return getClosestBSTNode( root, k, root.data() - k );
- }
- public Node getClosestBSTNode( Node node, int k, int parentDiff ){
- if( parentDiff == 0 ){
- return node;
- }
- Node closestLeftBSTNode = getClosestBSTNode( node.getLeft(), k, node.getData() - k );
- Node closestRightBSTNode = getClosestBSTNode( node.getRight(), k, node.getData() - k );
- if( parentDiff < ( closestLeftBSTNode.getData() - k) || parentDiff < ( closestRightBSTNode.getData() - k) ){
- return node;
- }
- if( Math.abs (closestLeftBSTNode.getData() - k) <= Math.abs( closestRightBSTNode.getData() - k ) ){
- return closestLeftBSTNode;
- } else{
- return closestRightBSTNode;
- }
- }
- // Method 2:
- public Node getClosestBSTNode( Node root ){
- return getClosestBSTNode( root, k );
- }
- public Node getClosestBSTNode( Node node, int k, Node closestNode ){
- if ( node == null ){
- return null;
- }
- int currData = node.data
- if( currData == k ){
- return node;
- } else if( currData < k ){
- int diff = Math.abs( currData - k );
- int closestDiff = Math.abs( closestNode.getData() - k );
- if( diff < closestDiff ){
- return getClosestBSTNode( node.getRight(), k, node );
- } else{
- return getClosestBSTNode( node.getRight(), k, closestNode );
- }
- } else if ( currData > k ){
- int diff = Math.abs( currData - k );
- int closestDiff = Math.abs( closestNode.getData() - k );
- if( diff < closestDiff ){
- return getClosestBSTNode( node.getLeft(), k, node );
- } else{
- return getClosestBSTNode( node.getLeft(), k, closestNode );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement