530.二叉搜索树的最小绝对差
题目
code
1.递归(中序遍历)转化为有序数组
/**
* 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 {
private:
vector<int> res;
void traversal(TreeNode* node )
{
if(node==NULL)
{
return;
}
traversal(node->left);
res.push_back(node->val); // 通过中序遍历,将二叉搜索树转换为有序数组
traversal(node->right);
}
public:
int getMinimumDifference(TreeNode* root) {
res.clear();
traversal(root);
int diff = INT_MAX;
for(int i =1;i<res.size();i++) //已转化为有序数组,递增所以后项减前项就可以得到正数差值
{
diff = min(diff,res[i]-res[i-1]);
}
return diff;
}
};
复杂度
501.二叉搜索树中的众数
题目
code
* 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 {
private:
int count = 0;
int maxcount = 0;
vector<int> res;
TreeNode* pre = NULL;
void searchBST(TreeNode* cur)
{
if(cur==NULL)
{
return; //递归终止条件
}
searchBST(cur->left); //左
//中
if(pre == NULL)
{
count = 1; //第一个节点
}
else if(pre->val==cur->val)
{
count += 1; //前后值相同
}
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); //重新加入结果
}
searchBST(cur->right); //右
}
public:
vector<int> findMode(TreeNode* root) {
searchBST(root);
return res;
}
};
复杂度
236. 二叉树的最近公共祖先
题目
code
/**
* 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 == q || root == p || root == NULL) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
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;
}
}
};