LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
1 class Solution { 2 public: 3 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 if(root->val >= p->val && root->val <= q->val || root->val >= q->val && root->val <= p->val) return root; 5 if(root->val > p->val) return lowestCommonAncestor(root->left, p, q); 6 return lowestCommonAncestor(root->right, p, q); 7 } 8 };
注意等号,因为root可能等于p或q。

浙公网安备 33010602011771号