文档讲解:
后序遍历,哨兵节点,二叉搜索树
思路:请注意二叉搜索树的特点,使用中序遍历去遍历它,可以得到一个有序数组,只要存在有序的特点,求解 很多问题都是迎刃而解的!特别是差值,最大值的问题,可以将二叉树转换成数组来解决
将二叉树转化成数组来解决!:
class Solution {
public:
vector<int> result;
void inorder(TreeNode* node)
{
if(node==nullptr)return;
inorder(node->left);
result.push_back(node->val);
inorder(node->right);
}
int getMinimumDifference(TreeNode* root) {
result.clear();
inorder(root);
int ans=INT_MAX;
for(int i=0;i<result.size()-1;++i)
{
ans=ans>abs(result[i]-result[i+1])?abs(result[i]-result[i+1]):ans;
}
return ans;
}
};
利用pre去存二叉树中的前一个节点!(这种做法得记一下),下次遇见了也可以这样去思考!
class Solution {
public:
int result=INT_MAX;
TreeNode* pre=nullptr;
void inordertraversal(TreeNode* root)
{
if(root==nullptr)return;
inordertraversal(root->left);
if(pre!=nullptr)
{
result=min(result,abs(root->val-pre->val));
}
pre=root;
inordertraversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
inordertraversal(root);
return result;
}
};
501.二叉搜索树中的众数
思路:最开始拿到这道题的时候,就想用hashmap,暴力做出来了,是方法一,但是这种做法有个缺点,没有利用到二叉搜索树的特点,适合普通二叉树的做法。
哈希表:
class Solution {
public:
unordered_map<int,int> map;
void inorder(TreeNode* node)
{
if(node==nullptr)return;
inorder(node->left);
map[node->val]++;
inorder(node->right);
}
vector<int> findMode(TreeNode* root) {
inorder(root);
vector<int> result;
int resmax=INT_MIN;
for(auto m:map)
{
resmax=m.second>resmax?m.second:resmax;
}
for(auto m:map)
{
if(m.second==resmax)
{
result.push_back(m.first);
}
}
return result;
}
};
双指针的妙解,充分利用二叉搜索树的特点!
class Solution {
public:
vector<int> result;
TreeNode* pre=nullptr;
int maxcount=0;
int count=0;
void inorder(TreeNode* root)
{
if(root==nullptr)return;
inorder(root->left);
//处理节点
if(pre==nullptr)
{
count=1;
}else if (pre->val==root->val)
{
count++;
}
else
{
count=1;
}
if(count==maxcount)
{
result.push_back(root->val);
}
if(count>maxcount)
{
maxcount=count;
result.clear();
result.push_back(root->val);
}
pre=root;
inorder(root->right);
}
vector<int> findMode(TreeNode* root) {
maxcount=0;
count=0;
pre=nullptr;
inorder(root);
return result;
}
};
思路:最开始拿到这道题没有思路,还是要学会自下向上的递归遍历!
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==nullptr||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;
else if(left==nullptr&&right)return right;
else if(left&&right==nullptr)return left;
else return nullptr;
}
};