Lowest Common Ancestor of a Binary Search Tree Solutions in C++
Number 235
Difficulty Easy
Acceptance 50.0%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/// Author : Hao Chen// Date : 2015-07-17/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {while(root) {if (p->val > root->val && q->val > root->val) {root = root->right;continue;}if (p->val < root->val && q->val < root->val) {root = root->left;continue;}return root;}return NULL;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description//// Author : liuyubobobo/// Time : 2017-11-18#include <iostream>#include <cassert>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Recursive/// Time Complexity: O(lgn), where n is the node's number of the tree/// Space Complexity: O(h), where h is the height of the treeclass Solution {public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {assert(!p && !q);if(!root) return root;if(p->val < root->val && q->val < root->val)return lowestCommonAncestor(root->left, p, q);if(p->val > root->val && q->val > root->val)return lowestCommonAncestor(root->right, p, q);assert(p->val == root->val || q->val == root->val|| (root->val - p->val) * (root->val - q->val) < 0);return root;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description//// Author : liuyubobobo/// Time : 2018-12-16#include <iostream>#include <cassert>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Non-Recursive/// Time Complexity: O(lgn), where n is the node's number of the tree/// Space Complexity: O(1)class Solution {public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if(!root) return root;TreeNode* cur = root;while(cur) {if (p->val < cur->val && q->val < cur->val)cur = cur->left;else if (p->val > cur->val && q->val > cur->val)cur = cur->right;elsereturn cur;}return NULL;}};int main() {return 0;}