剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
思路
方法一:迭代
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 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 while(root != NULL) { 14 if(p->val < root->val && q->val < root->val) { 15 root = root->left; 16 } else if(p->val > root->val && q->val > root->val) { 17 root = root->right; 18 } else { 19 break; 20 } 21 } 22 23 return root; 24 } 25 };
方法二:递归
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 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 if(root->val < p->val && root->val < q->val) 14 return lowestCommonAncestor(root->right, p, q); 15 if(root->val > p->val && root->val > q->val) 16 return lowestCommonAncestor(root->left, p, q); 17 return root; 18 } 19 };