bottom-up
package test.ui; import java.util.HashSet; import java.util.Set; public class test { //unsigned 2^32-1 so we need a long to instead. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public TreeNode LAC(TreeNode root, TreeNode l, TreeNode r){ if(root == null) return null; if(root == l || root == r) return root; TreeNode left = LAC(root.left,l,r); TreeNode right = LAC(root.right,l,r); if(left!=null && right!=null) return root; return left!=null?left:right; } public TreeNode buildTree(){ TreeNode root = new TreeNode(3); root.left = new TreeNode(5); root.right = new TreeNode(1); root.left.left = new TreeNode(6); root.left.right = new TreeNode(2); root.left.right.left = new TreeNode(7); root.left.right.right = new TreeNode(4); root.right.left = new TreeNode(0); root.right.right = new TreeNode(8); return root; } public static void main(String[] args) { // TODO Auto-generated method stub test t = new test(); TreeNode root = t.buildTree(); System.out.print(t.LAC(root, root.left.left, root.left.right.right).val); } }