题目大意:已知一个BST,找到BST中的节点p+q的最小公共祖先;
思路:递归
1 boundary conditions: tree, p, q任意为null, 返回null
2 如果p.va, q.val均小于root.val -> 说明p,q都在左子树-> return LowestCommonAncestor(root.left, p, q);
3 如果p.va, q.val均大于root.val -> 说明p,q都在右子树-> return LowestCommonAncestor(root.right, p, q);
4 否则,说明一左一右->root即为最小公共祖先
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p == null || q == null || root == null)
{
return null;
}
if (p.val < root.val && q.val < root.val)
{
return LowestCommonAncestor(root.left, p, q);
}
else if (p.val > root.val && q.val > root.val)
{
return LowestCommonAncestor(root.right, p, q);
}
else
{
return root;
}
}