Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. ublic int bstDistance(int[] nums, int node1, int node2) {
  2.     TreeNode root = buildBST(nums, node1, node2);
  3.     if (root == null) return -1;
  4.     TreeNode lca = lca(root, node1, node2);
  5.     return getDistance(lca, node1) + getDistance(lca, node2);
  6. }
  7.  
  8. private int getDistance(TreeNode src, int dest) {
  9.     if (src.val == dest) return 0;
  10.     TreeNode node = src.left;
  11.     if (src.val < dest) {
  12.         node = src.right;
  13.     }
  14.     return 1 + getDistance(node, dest);
  15. }
  16.  
  17. private TreeNode lca(TreeNode root, int node1, int node2) {
  18.     while (true) {
  19.         if (root.val > node1 && root.val > node2) {
  20.             root = root.left;
  21.         } else if (root.val < node1 && root.val < node2) {
  22.             root = root.right;
  23.         } else {
  24.             return root;
  25.         }
  26.     }
  27. }
  28.  
  29. private TreeNode buildBST(int[] nums, int node1, int node2) {
  30.     TreeNode root = null;
  31.     boolean found1 = false;
  32.     boolean found2 = false;
  33.     for (int val : nums) {
  34.         if (val == node1) found1 = true;
  35.         if (val == node2) found2 = true;
  36.        
  37.         TreeNode node = new TreeNode(val);
  38.         if (root == null) {
  39.             root = node;
  40.             continue;
  41.         }
  42.         addToBST(root, node);
  43.     }
  44.     if (!found1 || !found2) return null;
  45.     return root;
  46. }
  47.  
  48. private void addToBST(TreeNode root, TreeNode node) {
  49.     for (TreeNode curr = root; true; ) {
  50.         if (curr.val > node.val) {
  51.             if (curr.left == null) {
  52.                 curr.left = node;
  53.                 break;
  54.             } else {
  55.                 curr = curr.left;
  56.             }
  57.         } else {
  58.             if (curr.right == null) {
  59.                 curr.right = node;
  60.                 break;
  61.             } else {
  62.                 curr = curr.right;
  63.             }
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement