思路:
后序遍历。
实现:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 14 { 15 if (root == NULL or root == p or root == q) return root; 16 TreeNode* l = lowestCommonAncestor(root->left, p, q); 17 TreeNode* r = lowestCommonAncestor(root->right, p, q); 18 if (l == p) 19 { 20 if (r == q) return root; 21 else return l; 22 } 23 else if (l == q) 24 { 25 if (r == p) return root; 26 else return l; 27 } 28 else if (l == NULL) return r; 29 else return l; 30 } 31 };