LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Search Tree
阿新 • • 發佈:2018-08-25
lowest node nan stc leet common lca ear 尋找
236. Lowest Common Ancestor of a Binary Tree
遞歸尋找p或q,如果找到,層層向上返回,知道 root 左邊和右邊都不為NULL:if (left!=NULL && right!=NULL) return root;
時間復雜度 O(n),空間復雜度 O(H)
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root==NULL) returnNULL; if (root==p || root==q) return root; TreeNode *left=lowestCommonAncestor(root->left,p,q); TreeNode *right=lowestCommonAncestor(root->right,p,q); if (left!=NULL && right!=NULL) return root; if (left!=NULL) return left; if (right!=NULL) returnright; return NULL; } };
235. Lowest Common Ancestor of a Binary Search Tree
實際上比上面那題簡單,因為LCA的大小一定是在 p 和 q 中間,只要不斷縮小直到在兩者之間就行了。
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root->val>p->val && root->val>q->val)return lowestCommonAncestor(root->left,p,q); if (root->val<p->val && root->val<q->val) return lowestCommonAncestor(root->right,p,q); return root; } };
LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Search Tree