首页 > 其他 > 详细

Lowest Common Ancestor

时间:2016-07-08 06:42:59      阅读:204      评论:0      收藏:0      [点我收藏+]

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

Example

For the following binary tree:

  4
 / 3   7
   /   5   6

LCA(3, 5) = 4

LCA(5, 6) = 7

LCA(6, 7) = 7

分析:

面试时一定问清楚是BT还是BST。

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: The root of the binary search tree.
15      * @param A and B: two nodes in a Binary.
16      * @return: Return the least common ancestor(LCA) of the two nodes.
17      */
18 
19     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
20         // write your code here
21         if (contains(root.left, A) && contains(root.left, B)) return lowestCommonAncestor(root.left, A, B);
22         if (contains(root.right, A) && contains(root.right, B)) return lowestCommonAncestor(root.right, A, B);
23         return root;
24         
25     }
26     
27     public boolean contains(TreeNode root, TreeNode node) {
28         if (root == null) return false;
29         if (root == node) {
30             return true;
31         } else {
32             return contains(root.left, node) || contains(root.right, node);
33         }
34     }
35 }

 

Lowest Common Ancestor

原文:http://www.cnblogs.com/beiyeqingteng/p/5652083.html

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