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;
      }
    }
  • 相关阅读:
    vue获取下拉框值
    vue子父组件通信
    内存堆栈问题
    Object.defineProperty()--数据劫持原理
    call和apply和bind的区别
    Object.create()和new object()和{}的区别
    Object.keys()/Object.values()的简单理解
    object.assign
    泛型的定义、使用
    ts 泛型
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12529845.html
Copyright © 2011-2022 走看看