leetcode 230 Kth Smallest Element in a BST C++
来源:互联网 发布:天津中年同志软件 编辑:程序博客网 时间:2024/05/22 00:25
先用简单的方法,中序遍历放到一个数组里面,取k-1即可。
vector<int> vec; void inorder(TreeNode *root) { if (!root) return; inorder(root->left); vec.push_back(root->val); inorder(root->right); } int kthSmallest(TreeNode* root, int k) { inorder(root); return vec[k-1]; }
但是效率比较低。
后来用了这种,直接在递归的过程中找,因为每次遍历都相当于拿到了一个节点,并且是递增的。
int val = 0; int sum = 0; int numK; void inorder(TreeNode *root) { if(!root) return; inorder(root->left); if(++sum == numK) { val = root->val; return; } inorder(root->right); } int kthSmallest(TreeNode* root, int k) { numK = k; inorder(root); return val; }
0 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- Python源码学习笔记 3 字符串对象
- Largest Rectangle in a Histogram POJ
- 关于JS的逻辑运算题之if的使用
- Hibernate总结笔记之三
- eclipse git 提交时提示 “There are no staged files”
- leetcode 230 Kth Smallest Element in a BST C++
- Python编程:从入门到实践读书笔记-7 用户输入和while循环
- 扫雷小游戏
- 【ZOJ3953 The 17th Zhejiang University Programming Contest F】【贪心 or 费用流】Intervals 删最少线段使得每点最多2次覆盖
- LeetCode- 108/109. Convert Sorted Array/List to Binary Search Tree (JAVA)
- Path&PathMeasure完全解析
- 初尝Java异步编程
- 简述值类型和引用类型的区别
- table表格的一个css代码