530.二叉搜索树的最小绝对差
思路:中序遍历搜索二叉树,使用双指针来计算绝对值。
代码:
/**
* 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 res=INT_MAX;
TreeNode* pre=NULL;
void traversal(TreeNode* node){
if(node==NULL) return;
traversal(node->left);
if(pre!=NULL){
res=min(res,node->val-pre->val);
}
pre=node;
traversal(node->right);
return;
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return res;
}
};
501.二叉搜索树中的众数
思路:同样使用双指针,中序遍历,同时记录频率和当前最大频率,不断更新最大频率和重置结果数组。
代码:
/**
* 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> res;
TreeNode* pre=NULL;
void traversal(TreeNode* cur){
if(cur==NULL)
return;
traversal(cur->left);
if(pre==NULL)
count=1;
else if (pre->val == cur->val)
count++;
else
count=1;
pre=cur;
if(count==maxCount)
res.push_back(cur->val);
if(count>maxCount){
maxCount=count;
res.clear();
res.push_back(cur->val);
}
traversal(cur->right);
return;
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return res;
}
};
236. 二叉树的最近公共祖先
思路:后序遍历,遇到目标结点就返回。
代码:
/**
* 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==NULL) return NULL;
if(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&&right) return right;
else if(left&&!right) return left;
else return NULL;
}
};