-
class TreeNode {
-
public int value;
-
public TreeNode left;
-
public TreeNode right;
-
public TreeNode(int value) {
-
this.value = value;
- }
-
public TreeNode() {
- }
- }
-
public class TestTree {
-
public static int n;
-
ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>();
-
ArrayList<Integer> list = new ArrayList<Integer>();
-
public static void main(String[] args) {
-
int[] array = new int[] { 7,1,0,3,2,0,0,5,0,0,8,0,9,0,0};
-
TestTree t = new TestTree();
-
TreeNode root = t.CreateTreeBinary(new TreeNode(), array);
-
System.out.println(t.getLowestCommonAncestor(root, root, new TreeNode(2), new TreeNode(5)).value);
- }
-
public TreeNode CreateTreeBinary(TreeNode treeNode, int[] array) {
-
if (array[n] == 0) {
-
n++;
-
return null;
-
} else {
-
treeNode.value = array[n++];
-
treeNode.left = CreateTreeBinary(new TreeNode(0), array);
-
treeNode.right = CreateTreeBinary(new TreeNode(0), array);
-
return treeNode;
- }
- }
-
public static TreeNode getLowestCommonAncestor(TreeNode rootParent, TreeNode root,
-
TreeNode node1, TreeNode node2) {
-
if (root == null || node1 == null || node2 == null) {
-
return null;
- }
-
if ((root.value - node1.value) * (root.value - node2.value) < 0) {
-
return root;
-
} else if ((root.value - node1.value) * (root.value - node2.value) > 0) {
-
TreeNode newRoot = ((root.value > node1.value) && (root.value > node2.value)) ? root.left
-
: root.right;
-
return getLowestCommonAncestor(root, newRoot, node1, node2);
-
} else {
-
return rootParent;
- }
- }
- }