标签:
解法一:递归
1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 2 { 3 if (root == NULL || p == NULL || q == NULL) 4 return NULL; 5 6 if (root->val > p->val && root->val > q->val) 7 return lowestCommonAncestor(root->left, p, q); 8 else if (root->val < p->val && root->val < q->val) 9 return lowestCommonAncestor(root->right, p, q); 10 return root; 11 }
解法二:迭代
1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 2 { 3 if (root == NULL || p == NULL || q == NULL) 4 return NULL; 5 6 while (true) { 7 if (root->val < p->val && root->val < q->val) 8 root = root->right; 9 else if (root->val > p->val && root->val > q->val) 10 root = root->left; 11 else 12 break; 13 } 14 return root; 15 }
【LeetCode 235_二叉搜索树】Lowest Common Ancestor of a Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/mengwang024/p/4676150.html