1、二叉树最低公共父节点
题目描述:
构建一棵二叉树(不一定是二叉查找树),求出该二叉树中某两个结点的最低公共父结点。
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || root==p || root==q){
return root;
}
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
if(left!=null && right!=null){
return root;
//left 和 right 都不为空,说明p在该root.left子树中,q在root.right子树中。返回root作为根节点
}
else {
return left==null?right:left;
//若 left==null, 则说明 p,q 都不在 root.left子树中
//若 right==null, 则说明 p,q 都不在 root.right子树中
}
}
}
2.二叉搜索树公共父节点
递归版本:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val > p.val && root.val > q.val){
return lowestCommonAncestor(root.left, p, q);
}else if(root.val < p.val && root.val < q.val){
return lowestCommonAncestor(root.right, p, q);
}else{
return root;
}
}
}
非递归版本:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
if (root.val > p.val && root.val > q.val)
root = root.left;
else if (root.val < p.val && root.val < q.val)
root = root.right;
else
return root;
}
}
}