zoukankan      html  css  js  c++  java
  • [Algo] 127. Lowest Common Ancestor II

    Given two nodes in a binary tree (with parent pointer available), find their lowest common ancestor.

    Assumptions

    • There is parent pointer for the nodes in the binary tree

    • The given two nodes are not guaranteed to be in the binary tree

    Examples

            5

          /   

         9     12

       /        

      2    3      14

    The lowest common ancestor of 2 and 14 is 5

    The lowest common ancestor of 2 and 9 is 9

    The lowest common ancestor of 2 and 8 is null (8 is not in the tree)

    /**
     * public class TreeNodeP {
     *   public int key;
     *   public TreeNodeP left;
     *   public TreeNodeP right;
     *   public TreeNodeP parent;
     *   public TreeNodeP(int key, TreeNodeP parent) {
     *     this.key = key;
     *     this.parent = parent;
     *   }
     * }
     */
    public class Solution {
      public TreeNodeP lowestCommonAncestor(TreeNodeP one, TreeNodeP two) {
        // Write your solution here.
        int aLen = getHeight(one);
        int bLen = getHeight(two);
        if (aLen >= bLen) {
          return getLCANode(aLen - bLen, one, two);
        } else {
          return getLCANode(bLen - aLen, two, one);
        }
      }
    
      private int getHeight(TreeNodeP node) {
        int len = 0;
        while (node != null) {
          node = node.parent;
          len += 1;
        }
        return len;
      }
    
      private TreeNodeP getLCANode(int diff, TreeNodeP node, TreeNodeP other) {
        while (diff > 0) {
          node = node.parent;
          diff -= 1;
        }
        while (node != other) {
          node = node.parent;
          other = other.parent;
        }
        return node;
      }
    }
  • 相关阅读:
    221. Add Two Numbers II【medium】
    167. Add Two Numbers【easy】
    544. Top k Largest Numbers【medium】
    413. Reverse Integer【easy】
    219. Insert Node in Sorted Linked List【Naive】
    java发展史与java的语言特性
    MySQL级联删除的问题
    mac上创建MySQL的基本步骤
    MySQL中的约束简单使用
    MySQL的中文编码问题
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12529845.html
Copyright © 2011-2022 走看看