题解 | 妙策
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
public class Solution { public int lowestCommonAncestor (TreeNode root, int o1, int o2) { return (LCA(root, o1, o2)).val; } public static TreeNode LCA(TreeNode root, int o1, int o2){ if(root == null || root.val == o1 || root.val==o2){ return root; } TreeNode left = LCA(root.left, o1, o2); TreeNode right = LCA(root.right, o1, o2); //如果左树和右树都不为空,则返回头部 if(left != null && right != null){ return root; } return left != null ? left : right; } }