JZ86 在二叉树中找到两个节点的最近公共祖先
在二叉树中找到两个节点的最近公共祖先_牛客题霸_牛客网 (nowcoder.com)
//递归
import java.util.*;
public class Solution {
public int lowestCommonAncestor (TreeNode root, int val1, int val2) {
//空树return-1
if(root==null){
return -1;
}
//val1或者val2为根节点
if(root.val==val1||root.val==val2){
return root.val;
}
//左子树寻找公共祖先
int left=lowestCommonAncestor(root.left,val1,val2);
//右子树寻找公共祖先
int right=lowestCommonAncestor(root.right,val1,val2);
//左子树没找到,则在右子树
if(left==-1){
return right;
}
//右子树没找到,则在左子树
if(right==-1){
return left;
}
//否则为根节点
return root.val;
}
}