对于树类题目, 状态存储在当前节点的返回值, 递归到每个节点的返回值都是当前节点的值和左子树与右子树的返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; if (root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) return root; else if (left == null && right != null) return right; else return left; } }
|