首页 > 其他 > 详细

[Algo] 127. Lowest Common Ancestor II

时间:2020-03-20 13:38:38      阅读:46      评论:0      收藏:0      [点我收藏+]

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;
  }
}

 

[Algo] 127. Lowest Common Ancestor II

原文:https://www.cnblogs.com/xuanlu/p/12529845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!