Title Description
Enter two tree nodes, they are seeking the lowest common ancestor.
[Cow brush off questions address network] No
Ideas analysis
The question we must first determine whether a binary tree, but also to determine whether the binary search tree, if there is a parent pointer, or just plain binary tree.
- When the tree is a binary search tree, the lowest common ancestor node size between two tree node size.
- When the tree is a common tree traversal using information passed up the child nodes. In the left and right sub-tree to find out if there are two tree nodes, tree nodes if the two were about sub-tree, indicating that the root is their lowest common ancestor.
Test Case
- Functional Test: ordinary tree, tree left oblique and right oblique tree
- Special tests: null
Java code
public class Offer068 {
public static void main(String[] args) {
test1();
test2();
test3();
}
/*
* 二叉搜索树
* 利用大小关系即可
*/
public TreeNode getLowestCommonParentBST(TreeNode root,TreeNode node1,TreeNode node2) {
while(true) {
if(root==null)
return root;
if(root.val<node1.val && root.val<node2.val)
root=root.right;
else if(root.val>node1.val && root.val>node2.val)
root=root.left;
else
return root;
}
}
/*
* 普通二叉树
* 将下面结点的信息利用递归s往上传递
*/
public TreeNode getLowestCommonParent(TreeNode root,TreeNode node1,TreeNode node2) {
if(root==null || root== node1 || root== node2)
return root;
TreeNode left=getLowestCommonParent(root.left, node1, node2);
TreeNode right=getLowestCommonParent(root.right, node1, node2);
return left==null? right:right==null? left:root;
// 上面这句代码就是:
// if(left==null) {
// return right;
// }else {
// if(right==null)
// return left;
// else
// return root;
// }
}
private static void test1() {
}
private static void test2() {
}
private static void test3() {
}
}