文章目录
- 一、题目
- 二、解法
- 三、完整代码
所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。
一、题目
二、解法
思路分析:本题和这道题类似【算法与数据结构】236、LeetCode二叉树的最近公共祖先,相同的算法也能解这道题,但是没有充分利用到二叉搜索树的性质,二叉搜索树的性质为中间节点的键值大于所有左子树节点的键值,大于所有右子树的键值。因此要找到两个节点的最近祖先节点,只需要确定节点位于[p,q](或者是[q,p]大小未知,左闭右闭的区间)区间内。那么当节点键值比两个节点的键值都小时,说明公共最先节点在右子树内,遍历右子树即可,反之亦然,最终剩下的就是最近公共祖先节点。
程序如下:
class Solution {
public:
// 后序遍历: 左右中
// 1、输入参数
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2、终止条件
if (root == NULL) return root; // 如果节点相等或者是空节点返回
// 3、单层递归逻辑
if ((root->val > q->val && root->val > p->val)) {
TreeNode* left = lowestCommonAncestor(root->left, p, q); // 左
if (left != NULL) return left;
}
if ((root->val < q->val && root->val < p->val)) {
TreeNode* right = lowestCommonAncestor(root->right, p, q); // 右
if (right != NULL) return right;
}
return root;
}
};
三、完整代码
# include <iostream>
# include <vector>
# include <string>
# include <queue>
using namespace std;
// 树节点定义
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、输入参数
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2、终止条件
if (root == NULL) return root; // 如果节点相等或者是空节点返回
// 3、单层递归逻辑
if ((root->val > q->val && root->val > p->val)) {
TreeNode* left = lowestCommonAncestor(root->left, p, q); // 左
if (left != NULL) return left;
}
if ((root->val < q->val && root->val < p->val)) {
TreeNode* right = lowestCommonAncestor(root->right, p, q); // 右
if (right != NULL) return right;
}
return root;
}
};
// 前序遍历迭代法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
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;
}
// 前序遍历,找二叉树中指定的键值
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()
{
// 构建二叉树
vector<string> t = { "6", "2", "0", "NULL", "NULL", "4", "3", "NULL", "NULL", "5", "NULL", "NULL", "8", "7", "NULL", "NULL", "9", "NULL", "NULL" }; // 前序遍历
my_print(t, "目标树");
TreeNode* root = new TreeNode();
Tree_Generator(t, root);
vector<vector<int>> tree = levelOrder(root);
my_print2<vector<vector<int>>, vector<int>>(tree, "目标树:");
// 构建p, q节点
int p = 2, q = 8;
TreeNode* P_node = traversal_preOrder(root, p);
TreeNode* Q_node = traversal_preOrder(root, q);
// 找最近公共祖先节点
Solution s;
TreeNode* result = s.lowestCommonAncestor(root, P_node, Q_node);
cout << "节点 " << P_node->val << " 和节点 " << Q_node->val << " 的最近公共祖先节点为 " << result->val << endl;
system("pause");
return 0;
}
end