2018-03-27 LCA问题
二叉树最近公共祖先问题:一棵树根节点root,两个节点u和v,求最近公共祖先问题 如果是二叉搜索树:则如果root在u和v之间,则返回root;如果root比u和v都大,则取root的左子树找 样例代码如下
public TreeNode LCA(TreeNode root, TreeNode u, TreeNode v) {
TreeNode small = null, big = null;
if (u.val < v.val) {
small = u;
big = v;
}
else {
small = v;
big = u;
}
while(root != null) {
if (root.val < small)
root = root.right;
else if (root.val > big)
root = root.left;
else
return root;
}
return null;
}
如果是普通二叉树:
TreeNode LCA(TreeNode root, TreeNode u, TreeNode v) {
if (root == null)
return null;
if (root == u || root == v)
return root;
TreeNode left = getLCA(root.left, u, v);
TreeNode right = getLCA(root,right, u, v);
if (left != null && right != null)
return root;
else if (left != null)
return left;
else if (right != null)
return right;
else
return null; }
Written on March 27, 2018