首页 > 代码库 > Lowest Common Ancestor of a Binary Search Tree & a Binary Tree
Lowest Common Ancestor of a Binary Search Tree & a Binary Tree
235. Lowest Common Ancestor of a Binary Search Tree
题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/#/description
题目大意:给定一棵二叉查找树和两个节点p和q,要求返回这两个节点的第一个公共祖先。
思路:对于当前节点node,如果p和q的val都大于node的val,则说明p和q的第一个公共祖先在node的右子树,如果p和q的val都小于node的val,则说明p和q的第一个公共祖先在node的左子树,否则node就是p和q的第一个公共祖先。
算法步骤:(1)如果root->val > max(p->val, q->val),令root = root->left,调回步骤(1),否则,如果root->val < min(p->val, q->val),令root = root->right,调回步骤(1),否则返回root。
算法复杂度:时间复杂度为O(log(n)),空间复杂度为O(1)
代码:
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 (true) { 14 if (root->val > max(p->val, q->val)) 15 root = root->left; 16 else if (root->val < min(p->val, q->val)) 17 root = root->right; 18 else 19 return root; 20 } 21 } 22 };
评测系统上运行结果:
236. Lowest Common Ancestor of a Binary Tree
题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/#/description
题目大意:给定一棵二叉树和两个节点p和q,要求返回这两个节点的第一个公共祖先。
思路:如果p和q都在某节点的左边,就到左子树中查找共同祖先。若都在右边,则在右子树中查找共同祖先。如果p和q不在同一边,那就表示已经找到第一个共同祖先。
复杂度分析:时间复杂度为O(n),空间复杂度为O(n)
代码:
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 || root == p || root == q) 14 return root; 15 auto left = lowestCommonAncestor(root->left, p, q); 16 auto right = lowestCommonAncestor(root->right, p, q); 17 if (left && right) 18 return root; 19 return left ? left : right; 20 } 21 };
评测系统上运行结果:
Lowest Common Ancestor of a Binary Search Tree & a Binary Tree