The problem:

Given node P and node Q in a binary tree T.

Find out the lowest common ancestor of the two nodes.

Analysis:

The answer of this problem could only be the following two cases:

case 1: P or Q itself is the lowest common ancestor.

P

.........

X  Q

case 2: P and Q are in the different sub-trees of a node.

A

..........

P    Q

Additional Condition:

1. If the nodes in the tree has the parent pointer.

solution 1:  Starting from node P and Q, traverse along the parent link back to the root, compute the distance of P to root and Q to root respectively.

Compute the difference d of those two distances. Move the node with longer distance d nodes along parent link. Then begin move P and Q one node each time back to root, and check the nodes of P and Q point to, if the nodes are the same node, return the node.

  1. private TreeNode find_CLA(TreeNode root, TreeNode p, TreeNode q) {
  2. if (root == null)
  3. return null;
  4. if (p == null && q != null)
  5. return q;
  6. if (p != null && q == null)
  7. return p;
  8. int dist_p, dist_q, dist_diff;
  9. TreeNode temp;
  10. temp = p;
  11. while (temp != root) {
  12. temp = temp.parent;
  13. dist_p++;
  14. }
  15. temp = q;
  16. while (temp != root) {
  17. temp = temp.parent;
  18. dist_q++;
  19. }
  20. if (dist_p > dist_q) {
  21. dist_diff = dist_p - dist_q;
  22. temp = p;
  23. }else {
  24. dist_diff = dist_q - dist_p;
  25. temp = q;
  26. }
  27. while (dist_diff > 0) {
  28. temp = temp.parent;
  29. dist_diff--;
  30. }
  31. while (p != root) {
  32. if (p == q)
  33. return p;
  34. p = p.parent;
  35. q = p.parent;
  36. }
  37. return root;
  38. }

Solution 2. Use a Hashset.

The basic idea underlying this method is to use a hashset to record all nodes from P to root. then starting fom q to root, we check each node along this path. if the node appear in the hashset, then the node is the lowest common ancestor.

  1. private TreeNode find_LCA(TreeNode root, TreeNode p, TreeNode q) {
  2. if (root == null)
  3. return null;
  4. if (p == null || q != null)
  5. return q;
  6. if (p != null || q == null)
  7. return p;
  8. Set<TreeNode> hashset = new HashSet<TreeNode> ();
  9. while (p != root) {
  10. hashset.add(p);
  11. p = p.parent;
  12. }
  13. while (q != root) {
  14. if (hashset.contains(p)){
  15. return p;
  16. }
  17. }
  18. return root;
  19. }

What if we don't have parent pointer?

The problem gets complicated because we need to search all possible branches. But the idea behind it is also very elegant : use recursion!!!

The basic idea:

Since the problem is to find the lowest common ancestor, at each node, we would not be able to know its children in just one time traversaL.

Thus we choose to search through bottom-up way. Bottom-up way could be easily achieved through post-order traversal.

The invariant in recursion: (at each node)

Key idea: Once we encouter p or q, we return its pointer. Only LCA could be possible to have two sub-child-functions (not null).

1. We check if the current node is P or Q.  Iff true, we return current node, and stop searching along this branch.

2. If the current node is neither P or Q.  We check it's two sub-child-functions.

2.1 Iff two sub-children-functions's return value is not null, then the current node must be the LCA, we return it directly.

2.2 Iff only one branch's return value is not null,  return pass the branch's return value into the current node's pre level.

Note: The return value could be the LCA or just p or q's reference.

2.3. Iff both branch's return value is null, pass the null into pre level.

Key : the null pointer here is very important, it helps to indicate whether a branch contains target node or any node in {P, Q}

  1. private TreeNode find_LCA(TreeNode root, TreeNode p, TreeNode q) {
  2. if (root == null)
  3. return null;
  4. if (root == p || root == q)
  5. return root;
  6. TreeNode left = find_LCA(root.left, p, q);
  7. TreeNode right = find_LCA(root.right, p, q);
  8. if (left && right)
  9. return root;
  10. return left ? left : right;
  11. }

Lowest Common Ancestor in Binary Tree的更多相关文章

  1. 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

  2. [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  3. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  4. [LeetCode]Lowest Common Ancestor of a Binary Search Tree

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  5. 数据结构与算法(1)支线任务4——Lowest Common Ancestor of a Binary Tree

    题目如下:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, fin ...

  6. Lowest Common Ancestor of a Binary Search Tree

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  7. Lowest Common Ancestor of a Binary Tree

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  8. leetcode 235. Lowest Common Ancestor of a Binary Search Tree

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  9. leetcode 236. Lowest Common Ancestor of a Binary Tree

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

随机推荐

  1. jboss 7 as1 日志配置

    原文地址:https://docs.jboss.org/author/display/AS71/Logging+Configuration Overview The overall server lo ...

  2. jsp带参转链接

    1.jsp:forward page <jsp:forward page="show.jsp"> <jsp:param name="data" ...

  3. 给Sublime Text2安装轻量级代码提示插件:SublimeCodeIntel

    步骤: 1.下载SublimeCodeIntel(地址https://github.com/SublimeCodeIntel/SublimeCodeIntel): 2.将下载的压缩包解压,并放置在Pa ...

  4. (转)Smarty Foreach 使用说明

    foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案). foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是 ...

  5. SQL server 使用触发器跨数据库备份数据

    create database TriggerTest create table transInfo2 --交易信息表 ( cardID ) not null, --卡号 transType ) no ...

  6. Looper Handler MessageQueue Message 探究

    Android消息处理的大致的原理如下: 1.有一个消息队列,可以往队列中添加消息 2.有一个消息循环,可以从消息队列中取出消息 Android系统中这些工作主要由Looper和Handler两个类来 ...

  7. Getting Started with Testing ——开始单元测试

    Android tests are based on JUnit, and you can run them either as local unit tests on the JVM or as i ...

  8. session marked for kill处理oracle中杀不掉的锁

    ora-00031:session marked for kill处理oracle中杀不掉的锁   一些ORACLE中的进程被杀掉后,状态被置为"killed",但是锁定的资源很长 ...

  9. C蛮的全栈之路-序章 技术栈选择与全栈工程师

    目录 C蛮的全栈之路-序章 技术栈选择与全栈工程师C蛮的全栈之路-node篇(一) 环境布置C蛮的全栈之路-node篇(二) 实战一:自动发博客 博主背景 985院校毕业,至今十年C++开发工作经验, ...

  10. POJ 1286 Necklaces of Beads (Burnside定理,有限制型)

    题目链接:http://vjudge.net/problem/viewProblem.action?id=11117 就是利用每种等价情形算出置换节之后算组合数 #include <stdio. ...