daily pastebin goal
70%
SHARE
TWEET

Untitled

a guest Mar 24th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Node(val) {
  2.     this.val = val;
  3.     this.left = null;
  4.     this.right = null;
  5. }
  6.  
  7. function commonParent(root, val1, val2) {
  8.     if (root == null) return null;
  9.  
  10.     if (root.val == val1 || root.val == val2) return root;
  11.  
  12.     let left = commonParent(root.left, val1, val2);
  13.     let right = commonParent(root.right, val1, val2);
  14.  
  15.     if (left != null && right != null) return root;
  16.     else if (left == null) return right;
  17.     else return left;
  18. }
  19.  
  20. function createNode(val) {
  21.     return new Node(val);
  22. }
  23.  
  24. let n2 = createNode(2);
  25. let n4 = createNode(4);
  26. let n5 = createNode(5);
  27. let n8 = createNode(8);
  28. let n9 = createNode(9);
  29. let n10 = createNode(10);
  30. let n11 = createNode(11);
  31.  
  32. n2.left = n4;
  33. n2.right = n5;
  34. n4.left = n8;
  35. n4.right = n9;
  36. n5.left = n10;
  37. n5.right = n11;
  38.  
  39. const commonNode = commonParent(n2, 8, 11);
  40. console.log(commonNode && commonNode.val);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top