当前位置: 首页 > news >正文

LeetCode Hot100 | Day4 | 层序遍历有序数组转搜索树验证搜索树搜索树中第K小的元素

LeetCode Hot100 | Day4 | 层序遍历&&有序数组转搜索树&&验证搜索树&&搜索树中第K小的元素

文章目录

  • LeetCode Hot100 | Day4 | 层序遍历&&有序数组转搜索树&&验证搜索树&&搜索树中第K小的元素
    • 102.二叉树的层序遍历
    • 108.将有序数组转换为二叉搜索树
    • 98.验证二叉搜索树
    • 230.二叉搜索树中第K小的元素

102.二叉树的层序遍历

102. 二叉树的层序遍历 - 力扣(LeetCode)

完整代码:

class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {vector<vector<int>> res;queue<TreeNode*> q;if(root==nullptr)return res;q.push(root);while(!q.empty()){int size=q.size();vector<int> path;for(int i=0;i<size;i++){TreeNode *t=q.front();q.pop();path.push_back(t->val);if(t->left)q.push(t->left);if(t->right)q.push(t->right);}res.push_back(path);}return res;}
};

108.将有序数组转换为二叉搜索树

108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)

层序遍历来做

class Solution {
public:TreeNode *tra(vector<int> nums){if(nums.size()==0)return nullptr;int index=nums.size()/2;TreeNode *t=new TreeNode(nums[index]);t->left=tra(vector<int>(nums.begin(),nums.begin()+index));t->right=tra(vector<int>(nums.begin()+index+1,nums.end()));return t;}TreeNode* sortedArrayToBST(vector<int>& nums) {return tra(nums);}
};

98.验证二叉搜索树

记得要用二叉搜索树的性质,中序遍历有序

98. 验证二叉搜索树 - 力扣(LeetCode)

class Solution {
public:TreeNode *pre=nullptr;bool tra(TreeNode *t,int maxVal){if(t==nullptr)return true;bool l=tra(t->left,maxVal);if(pre!=nullptr)if(t->val<=pre->val)return false;pre=t;bool r=tra(t->right,maxVal);return l&&r;}bool isValidBST(TreeNode* root) {int maxVal=INT_MIN;return tra(root,maxVal);}
};

230.二叉搜索树中第K小的元素

230. 二叉搜索树中第 K 小的元素 - 力扣(LeetCode)

1.转为有序数组

class Solution {
public:vector<int> nums;void tra(TreeNode *t){if(t==nullptr)return;tra(t->left);nums.push_back(t->val);tra(t->right);}int kthSmallest(TreeNode* root, int k) {tra(root);return *(nums.begin()+k-1);}   
};

2.中序遍历

每走过一个数,计数器count++,k==count的时候那就是结果了,res记录结果然后返回

后面的情况都不会发生res的覆盖了,因为count只会比k大

class Solution {
public:int res=0;int count=0;void tra(TreeNode *t,int k){if(t==nullptr)return;tra(t->left,k);count++;if(k==count){res=t->val;return;}tra(t->right,k);}int kthSmallest(TreeNode* root, int k) {tra(root,k);return res;}   
};

K神题解,一开始用的k–,但是发现会覆盖,就改成加了,没想到加个==0就行了

class Solution {
public:int kthSmallest(TreeNode* root, int k) {this->k = k;dfs(root);return res;}
private:int res, k;void dfs(TreeNode* root) {if (root == nullptr) return;dfs(root->left);if (k == 0) return;if (--k == 0) res = root->val;dfs(root->right);}

http://www.mrgr.cn/news/50014.html

相关文章:

  • ZFX山海证券的多元化产品策略
  • uniapp+veu3在vite.config.ts配置代理解决跨域问题
  • Python自动化脚本裁剪图片为1:1比例
  • javaweb-xml映射文件编写sql语句
  • 行星减速机:市场集中度较高
  • 海天瑞声携手中国移动共创AI+时代,以高质量AI训练数据驱动数智化发展
  • C++ 算法学习——1.8 状态剪枝
  • vue中watch和watchEffect区别
  • 画质修复软件哪个好?照片清晰用这些
  • 第 4 章:Vue 中的 ajax
  • 2011年国赛高教杯数学建模A题城市表层土壤重金属污染分析解题全过程文档及程序
  • 零基础搭建QQ机器人(Ⅱ)
  • osgEarth 键鼠 增删改 feature Node
  • 【Go初阶】两万字快速入门Go语言
  • 物资出入库二维码管理系统
  • 测量表面粗糙度:白光共聚焦显微镜的优点
  • 如何成为互联网信息挖掘机
  • C++ 内存管理 对比C语言动态内存管理;operator new和delete
  • java时间类-深入探究DateUtils的最佳实践
  • 倾斜的角标 android倾斜角标实现