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 }


 上面解法的复杂度还是太高了,为O(nlgn).

下面解法的复杂度是O(n).



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


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 BST.

According to the : “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5


For example, the lowest common ancestor (LCA) of nodes ​​2​​ and ​​8​​ is ​​6​​. Another example is LCA of nodes ​​2​​ and ​​4​​ is ​​2​​, since a node can be a descendant of itself according to the LCA definition.



1 /**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode(int x) { val = x; }
8 * }
9 */
10 public class Solution {
11 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12 if (p.val > q.val) return lowestCommonAncestor(root, q, p);
13
14 if (root.val < p.val) return lowestCommonAncestor(root.right, p, q);
15 if (root.val > q.val) return lowestCommonAncestor(root.left, p, q);
16
17 return root;
18 }
19 }