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;
      }
    }
  • 相关阅读:
    Flask从负到零的一周
    DOM(一):节点层次-Node类型
    错误处理(三):区分致命错误和非致命错误
    错误处理(二):常见错误类型
    错误处理(一)
    跨域(二)
    跨域(一)
    AJAX(四):XHR2支持的方法
    AJAX(三):GET与POST
    AJAX(二):HTTP头部信息
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12529845.html
Copyright © 2011-2022 走看看