二叉樹的最近公共祖先問題
阿新 • • 發佈:2020-12-11
一、普通二叉樹的公共祖先問題
/** * 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) {//求最近公共祖先,如果可以自底向上搜尋就好了,正好,後序遍歷就是自底向上的,所以採用後序遞迴遍歷框架 //遞迴終止條件base case if(root == nullptr) return nullptr; if(root == p || root == q) return root; //要遍歷整棵樹,先把遞迴的結果存起來,下面進行邏輯處理 TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); //如果p和q都在以root為根的樹中,那麼left好right一定是p和q(從base case得出) if(left != nullptr && right != nullptr) return root; //如果p和q都不在以root為根的樹中 if(left == nullptr && right == nullptr) return nullptr;//剩下的就是q和q只有一個存在與以root為根的樹中,函式返回該節點 return left == nullptr? right : left; } };
二、二叉搜尋樹的公共祖先問題
相比於普通二叉樹,二叉搜尋樹有一些特性,可以利用這些特性來改善演算法效能。
因為二叉樹搜尋樹的特性,其實只要從上到下遍歷的時候,遍歷的當前節點數值在[p,q]區間中說明該節點就是最近公共祖先了。
/** * 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) { //雖然按題意不會出現但還是判斷一下吧養成一個良好的習慣 if(root == nullptr) return root; //只搜尋一條邊,因為是二叉搜尋樹,如果在這條邊中,找到後直接返回 if(root->val > p->val && root->val > q->val) { TreeNode* left = lowestCommonAncestor(root->left, p, q); if(left != nullptr) return left; } if(root->val < p->val && root->val < q->val) { TreeNode* right = lowestCommonAncestor(root->right, p, q); if(right != nullptr) return right; } //剩下的幾種情況就是root就在[p,q]區間裡了,直接返回即可 return root; } };