题目描述:
给定一个数组tree和两个节点p,q,计算最低公共祖先的值。
输入:一个数组和两个节点值
输出:计算最低公共祖先的值
如:
输入:
1,2,3,4,5,6,7,-1,-1,8,9
4
3
输出:1
思路:
最低公共祖先的题目肯定会求,本题麻烦就在于要把输入的数组转换成二叉树,另外两个值转换成二叉树中的节点值。
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
val = x;
left = null;
right = null;
}
}
public class Main3 {
static TreeNode t1;
static TreeNode t2;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int p = sc.nextInt();
int q = sc.nextInt();
String[] strs = s.split(",");
int[] tree = new int[strs.length];
for(int i = 0; i < strs.length; i ++) {
tree[i] = Integer.parseInt(strs[i]);
}
TreeNode root = buildTree(tree, p, q);
TreeNode res = lowestCommonAncestor(root, t1, t2);
System.out.println(res.val);
}
public static TreeNode buildTree(int[] nums, int x, int y) {
if(nums == null || nums.length == 0) return null;
Queue<TreeNode> q = new LinkedList<>();
TreeNode root = new TreeNode(nums[0]);
q.offer(root);
int i = 1;
if(root.val == x) t1 = root;
if(root.val == y) t2 = root;
while(i < nums.length) {
int size = q.size();
while(size -- > 0 && i < nums.length) {
TreeNode node = q.poll();
node.left = new TreeNode(nums[i++]);
node.right = new TreeNode(nums[i++]);
q.offer(node.left);
q.offer(node.right);
if(node.left.val == x) t1 = node.left;
if(node.left.val == y) t2 = node.left;
if(node.right.val == x) t1 = node.right;
if(node.right.val == y) t2 = node.right;
}
}
return root;
}
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root.val == -1) return null;
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 || left.val == -1){
return right;
}else if(right == null || right.val == -1){
return left;
}else{
return root;
}
}
}