今天做题发现了一道对递归最佳辅助理解的题目:剑指 Offer 68 - II. 二叉树的最近公共祖先,二叉树对理解递归的帮助很大。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 if (root == null || root == p || root == q) { 13 return root; 14 } 15 TreeNode left = lowestCommonAncestor(root.left, p, q); 16 TreeNode right = lowestCommonAncestor(root.right, p, q); 17 if (left == null && right == null) { 18 return null; 19 } 20 if (left == null) { 21 return right; 22 } 23 if (right == null) { 24 return left; 25 } 26 return root; 27 } 28 }