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.
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 }
原文:http://www.cnblogs.com/beiyeqingteng/p/5652083.html