【LeetCode 235_二叉搜尋樹】Lowest Common Ancestor of a Binary Search Tree

QingLiXueShi發表於2015-07-25

解法一:遞迴

 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 }

 

相關文章