Advertisement
sweet1cris

Untitled

Jan 9th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. /**
  2.  * Definition of ParentTreeNode:
  3.  *
  4.  * class ParentTreeNode {
  5.  *     public ParentTreeNode parent, left, right;
  6.  * }
  7.  */
  8. public class Solution {
  9.     /**
  10.      * @param root: The root of the tree
  11.      * @param A, B: Two node in the tree
  12.      * @return: The lowest common ancestor of A and B
  13.      */
  14.     public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root,
  15.                                                  ParentTreeNode A,
  16.                                                  ParentTreeNode B) {
  17.         ArrayList<ParentTreeNode> pathA = getPath2Root(A);
  18.         ArrayList<ParentTreeNode> pathB = getPath2Root(B);
  19.        
  20.         int indexA = pathA.size() - 1;
  21.         int indexB = pathB.size() - 1;
  22.        
  23.         ParentTreeNode lowestAncestor = null;
  24.         while (indexA >= 0 && indexB >= 0) {
  25.             if (pathA.get(indexA) != pathB.get(indexB)) {
  26.                 break;
  27.             }
  28.             lowestAncestor = pathA.get(indexA);
  29.             indexA--;
  30.             indexB--;
  31.         }
  32.        
  33.         return lowestAncestor;
  34.     }
  35.    
  36.     private ArrayList<ParentTreeNode> getPath2Root(ParentTreeNode node) {
  37.         ArrayList<ParentTreeNode> path = new ArrayList<>();
  38.         while (node != null) {
  39.             path.add(node);
  40.             node = node.parent;
  41.         }
  42.         return path;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement