代码随想录刷题03.05
二叉树相关操作7
LeetCode题目
解题思路
1.搜索二叉树中的双指针法:定义一个pre指针,在中序遍历中pre指针可以跟着root指针回退。
2.在遇到全局变量时,优先选择void来实现变量的实时变化,这样可以省去返回值数据流的思考。
3.注意,"中"决定操作,"左右"起递归动力作用。
代码过程
/**
* Definition for a binary tree node.
* 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:
TreeNode* pre=nullptr;
int result=INT_MAX;
void travel(TreeNode* root){
if(root==nullptr)return;
travel(root->left);
if(pre!=nullptr)
result=min(result,root->val-pre->val);
pre=root;
travel(root->right);
return;
}
int getMinimumDifference(TreeNode* root) {
travel(root);
return result;
}
};
LeetCode题目
解题思路
1.本题的关键:利用搜索二叉树的双指针遍历方法统计相同元素出现的频率;
搜索二叉树的双指针遍历方法:
1)定义一个全局指针pre=nullptr;
2)在搜索二叉树中序逆遍历时,不断更新pre指针,pre=root.
2.本题的思路:
1)首先,利用双指针遍历法统计出相同元素出现的频率;
2)定义一个全局变量maxcount,在统计元素出现的频率后不断比较更新maxcount;
3)在更新maxcount时,向全局vector数组中加入元素。
3.本题易失误的点:元素出现频率count和储存容器result的更新需要确定好如何更新的方法。
代码过程
/**
* Definition for a binary tree node.
* 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:
int count=0;
int maxcount=0;
vector<int>result;
TreeNode* pre=nullptr;
vector<int> findMode(TreeNode* root) {
if(root==nullptr)return result;
findMode(root->left);
if(pre==nullptr)count=1;
else if(pre->val==root->val){
count++;
}
else{
count=1;
}
pre=root;
if(maxcount==count)result.push_back(root->val);
else if(maxcount<count){
maxcount=count;
result.clear();
result.push_back(root->val);
}
findMode(root->right);
return result;
}
};
LeetCode题目
解题思路
在父节点中判断子树中是否包含p或q,若包含,则返回子节点地址。
因此,需要采用后序遍历的方式,先左右子树再父节点;同时,父节点应有2个变量分别用于判断左右子树是否是否有p或q,不断向上返回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 nullptr;
if(root==p||root==q)return root;
TreeNode* left= lowestCommonAncestor(root->left,p,q);
TreeNode* right= lowestCommonAncestor(root->right,p,q);
if(left!=nullptr&&right!=nullptr)return root;
else if(left==nullptr&&right!=nullptr)return right;
else if(left!=nullptr&&right==nullptr)return left;
else return nullptr;
}
};