码迷,mamicode.com
首页 > 其他好文 > 详细

Lowest Common Ancestor

时间:2016-07-08 06:44:58      阅读:133      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!