题目大意:已知一个BT,找到BST中的节点p+q的最小公共祖先;
例子:
_______
3______
/ \___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
5,1 -> 3
5,4 -> 5 (允许一个node成为自己的descendant)
思路:
1 boundary conditions: root, p, q任意为null, 返回null
2 查看左子树中是否有目标结点,没有为null
3 都不为空,说明做右子树都有目标结点,则公共祖先就是本身
4 如果有一个为null, 返回另外一个;用三目表达式;
/**
* 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 class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//发现目标节点则通过返回值标记该子树发现了某个目标结点
if(root == null || root == p || root == q)
return root;
//查看左子树中是否有目标结点,没有为null
TreeNode left = LowestCommonAncestor(root.left, p, q);
//查看右子树是否有目标节点,没有为null
TreeNode right = LowestCommonAncestor(root.right, p, q);
//都不为空,说明做右子树都有目标结点,则公共祖先就是本身
if(left!=null&&right!=null) return root;
//如果发现了目标节点,则继续向上标记为该目标节点
return left == null ? right : left;
}
}