所有的LeetCode題解索引,可以看這篇文章——【算法和數(shù)據(jù)結(jié)構(gòu)】LeetCode題解。
一、題目
二、解法
??思路分析: 根據(jù)定義,最近祖先節(jié)點(diǎn)需要遍歷節(jié)點(diǎn)的左右子樹(shù),然后才能知道是否為最近祖先節(jié)點(diǎn)。那么這種需求是先遍歷左右節(jié)點(diǎn),然后遍歷中間節(jié)點(diǎn),屬于左右中的后序遍歷模式。因此在程序當(dāng)中,我們選擇遞歸中序遍歷。輸入?yún)?shù)為根節(jié)點(diǎn)p q節(jié)點(diǎn)。終止條件是當(dāng)前節(jié)點(diǎn)和p q當(dāng)中任意一個(gè)節(jié)點(diǎn)相等時(shí)就返回,遍歷到空節(jié)點(diǎn)也返回。因?yàn)槭呛笮虮闅v,根據(jù)遍歷完左右子樹(shù)后的返回值確定返回參數(shù),如果返回值都不為空,則當(dāng)前節(jié)點(diǎn)就是最近祖先節(jié)點(diǎn)。如果left為空,right不為空,則最近祖先節(jié)點(diǎn)在右子樹(shù),反之亦然。均為空則返回NULL。
??程序如下:
class Solution2 {
public:
// 后序遍歷: 左右中
// 1、輸入?yún)?shù)
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2、終止條件
if (root == q || root == p || root == NULL) return root; // 如果節(jié)點(diǎn)相等或者是空節(jié)點(diǎn)返回
// 3、單層遞歸邏輯
TreeNode* left = lowestCommonAncestor(root->left, p, q); // 左
TreeNode* right = lowestCommonAncestor(root->right, p, q); // 右
// 1、返回值
if (left != NULL && right != NULL) return root;
if (left == NULL && right != NULL) return right;
else if (left != NULL && right == NULL) return left;
else { // (left == NULL && right == NULL)
return NULL;
}
}
};
??代碼優(yōu)化:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-707836.html
class Solution {
public:
// 后序遍歷: 左右中
// 1、輸入?yún)?shù)
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2、終止條件
if (root == p || root == q || root == NULL) return root; // 如果節(jié)點(diǎn)相等或者是空節(jié)點(diǎn)返回
// 3、單層遞歸邏輯
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 right;
// 1、返回值
return left;
}
};
三、完整代碼
# include <iostream>
# include <vector>
# include <string>
# include <queue>
using namespace std;
// 樹(shù)節(jié)點(diǎn)定義
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
// 后序遍歷: 左右中
// 1、輸入?yún)?shù)
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2、終止條件
if (root == p || root == q || root == NULL) return root; // 如果節(jié)點(diǎn)相等或者是空節(jié)點(diǎn)返回
// 3、單層遞歸邏輯
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 right;
// 1、返回值
return left;
}
};
class Solution2 {
public:
// 后序遍歷: 左右中
// 1、輸入?yún)?shù)
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2、終止條件
if (root == q || root == p || root == NULL) return root; // 如果節(jié)點(diǎn)相等或者是空節(jié)點(diǎn)返回
// 3、單層遞歸邏輯
TreeNode* left = lowestCommonAncestor(root->left, p, q); // 左
TreeNode* right = lowestCommonAncestor(root->right, p, q); // 右
// 1、返回值
if (left != NULL && right != NULL) return root;
if (left == NULL && right != NULL) return right;
else if (left != NULL && right == NULL) return left;
else { // (left == NULL && right == NULL)
return NULL;
}
}
};
// 前序遍歷迭代法創(chuàng)建二叉樹(shù),每次迭代將容器首元素彈出(彈出代碼還可以再優(yōu)化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {
if (!t.size() || t[0] == "NULL") return; // 退出條件
else {
node = new TreeNode(stoi(t[0].c_str())); // 中
if (t.size()) {
t.assign(t.begin() + 1, t.end());
Tree_Generator(t, node->left); // 左
}
if (t.size()) {
t.assign(t.begin() + 1, t.end());
Tree_Generator(t, node->right); // 右
}
}
}
template<typename T>
void my_print(T& v, const string msg)
{
cout << msg << endl;
for (class T::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << ' ';
}
cout << endl;
}
template<class T1, class T2>
void my_print2(T1& v, const string str) {
cout << str << endl;
for (class T1::iterator vit = v.begin(); vit < v.end(); ++vit) {
for (class T2::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {
cout << *it << ' ';
}
cout << endl;
}
}
// 層序遍歷
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size(); // size必須固定, que.size()是不斷變化的
vector<int> vec;
for (int i = 0; i < size; ++i) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
// 前序遍歷,找二叉樹(shù)中指定的鍵值
TreeNode* traversal_preOrder(TreeNode* cur, int val) {
if (cur == NULL) return NULL;
if (cur->val == val) return cur; // 中
if (traversal_preOrder(cur->left, val) != NULL) return traversal_preOrder(cur->left, val); // 左
if (traversal_preOrder(cur->right, val) != NULL) return traversal_preOrder(cur->right, val); // 右
return NULL;
}
int main()
{
// 構(gòu)建二叉樹(shù)
vector<string> t = { "3", "5", "6", "NULL", "NULL", "2", "7", "NULL", "NULL", "4", "NULL", "NULL", "1", "0", "NULL", "NULL", "8", "NULL", "NULL"}; // 前序遍歷
my_print(t, "目標(biāo)樹(shù)");
TreeNode* root = new TreeNode();
Tree_Generator(t, root);
vector<vector<int>> tree = levelOrder(root);
my_print2<vector<vector<int>>, vector<int>>(tree, "目標(biāo)樹(shù):");
// 構(gòu)建p, q節(jié)點(diǎn)
int p = 5, q = 1;
TreeNode* P_node = traversal_preOrder(root, p);
TreeNode* Q_node = traversal_preOrder(root, q);
// 找最近公共祖先節(jié)點(diǎn)
Solution s;
TreeNode* result = s.lowestCommonAncestor(root, P_node, Q_node);
cout << "節(jié)點(diǎn) " << P_node->val << " 和節(jié)點(diǎn) " << Q_node->val << " 的最近公共祖先節(jié)點(diǎn)為 " << result->val << endl;
system("pause");
return 0;
}
end文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-707836.html
到了這里,關(guān)于【算法與數(shù)據(jù)結(jié)構(gòu)】236、LeetCode二叉樹(shù)的最近公共祖先的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!