NC102 在二叉树中找到两个节点的最近公共祖先
描述
给定一棵二叉树(保证非空)以及这棵树上的两个节点对应的val值 o1 和 o2,请找到 o1 和 o2 的最近公共祖先节点。
注:本题保证二叉树中每个节点的val值均不相同。
示例1
输入:
[3,5,1,6,2,0,8,#,#,7,4],5,1
复制
返回值:3
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
// write code here
if(root == null){
return -1 ;
}
if(root.val == o1 || root.val == o2){
return root.val ;
}
int left =lowestCommonAncestor(root.left , o1 , o2) ;
int right =lowestCommonAncestor(root.right , o1 , o2);
if(left != -1 && right != -1){
return root.val ;
}
if(left != -1){
return left ;
}
if(right != -1){
return right ;
}
return -1 ;
}
}