236. Lowest Common Ancestor of a Binary Tree
也是一遍AC,开心
和上题差不多,思路
1 如果root是null, 2 3 返回null 4 5 如果root==q或者root==p 6 7 返回root 8 9 left = 对左子树递归 10 11 right = 对右子树递归 12 13 如果两个都不为空(说明目标节点在当前节点两侧), 14 15 返回root 16 17 否则返回left和right里面不为空的那个
代码:
1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 2 if(root == null) { 3 return null; 4 } 5 if(root == p || root == q) { 6 return root; 7 } 8 TreeNode leftRes = lowestCommonAncestor(root.left, p, q); 9 TreeNode rightRes = lowestCommonAncestor(root.right, p, q); 10 if(leftRes != null && rightRes != null) { 11 return root; 12 } 13 return leftRes != null? leftRes: rightRes; 14 }