The problem is:
Given a binary tree (not a binary search tree) and two values say n1 and n2, write a program to find the least common ancestor.
思路:
Because it is binary tree, not BST, so we need to make more comparison. Use recursion and find the base cases.
1. 如果root是空,则说明此处没有需要的ancestor
2. 如果root的值等于所要求的两个点中的某一个,则设置存在标记flag,并且返回这个值作为共同祖先的值
3. 递归计算左右子树中是否有LCA
Java代码如下:
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int i) {
this.val = i;
}
}
public class LCA {
public TreeNode findLCA(TreeNode root, TreeNode l, TreeNode r, boolean[] flag) {
if (root == null) {
return null;
}
if (root.val == l.val) {
flag[0] = true;
return root;
}
if (root.val == r.val) {
flag[1] = true;
return root;
}
TreeNode leftLCA = findLCA(root.left, l, r, flag);
TreeNode rightLCA = findLCA(root.right, l, r, flag);
if (leftLCA != null && rightLCA != null) {
return root;
}
return (leftLCA != null) ? leftLCA: rightLCA;
}
public boolean find(TreeNode root, TreeNode node) {
if (root == null) {
return false;
}
if (root.val == node.val) {
return true;
}
return find(root.left, node) || find(root.right, node);
}
public TreeNode findLCA(TreeNode root, TreeNode l, TreeNode r) {
boolean[] flag = new boolean[2];
TreeNode LCA = findLCA(root, l, r, flag);
if (LCA == null) {
return null;
}
if (flag[0] && flag[1] || flag[0] && find(LCA, r) || flag[1] && find(LCA, l)) {
return LCA;
}
return null;
}
public static void main(String[] args) {
//test
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
LCA a = new LCA();
TreeNode lca = a.findLCA(root, new TreeNode(4), new TreeNode(5));
if (lca != null)
System.out.println(lca.val);
else
System.out.println("Keys are not present ");
lca = a.findLCA(root, new TreeNode(4), new TreeNode(10));
if (lca != null)
System.out.println(lca.val);
else
System.out.println("Keys are not present ");
}
}