(C++)LeetCode#236. Lowest Common Ancestor of a Binary Tree
阿新 • • 發佈:2019-02-15
- 題目:給定一個棵二叉樹的兩個節點o1/o2,求兩個節點的最近公共祖先(LCA)
- 難度:Medium
- 思路:
- 方法1.記錄路徑:先遍歷二叉樹,分別得到從根節點到o1/o2的兩個路徑儲存在vector中,遍歷兩個vector得到最近的相等的節點
- 方法2.不記錄路徑:通過先序遍歷二叉樹,先判斷當前遍歷的節點是否為o1/o2,如果是則直接返回當前節點,否則繼續遍歷左子樹、右子樹,如果左子樹返回結果和右子樹返回結果同時存在,說明當前節點為最近公共祖先;否則判斷左子樹返回結果是否為空,如果不為空則返回左子樹遍歷結果,為空就返回右子樹遍歷結果
- 程式碼:
方法一
class Solution {
public :
bool getAncestor(TreeNode* root, TreeNode* node, vector<TreeNode*> &vec) {
if (root == NULL) {
return false;
}
if (root == node) {
vec.push_back(root);
return true;
}
if (getAncestor(root->left, node, vec) || getAncestor(root->right, node, vec)) {
vec.push_back(root);
return true;
}
return false;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> lvec, rvec;//vector第一個節點是p或者q
getAncestor(root, p, lvec);
getAncestor(root, q, rvec);
TreeNode* ancestor;
int m = lvec.size();
int n = rvec.size();
while(m >0 && n > 0 && lvec[m-1]==rvec[n-1]){
m--;
n--;
}
return lvec[m];
}
};
方法二
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) {
return root;
}
return left?left:right;
}
};