LeetCode 230. Kth Smallest Element in a BST 解题报告
2016-10-20 22:27
591 查看
LeetCode 230. Kth Smallest Element in a BST 解题报告
题目描述
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
示例
没有给出限制条件
没有明确给出.解题思路
我的思路:
首先得补充说明一下,LeetCode里这道题它建立的树不是BST(二叉查找树),而是普通的一棵树,但是这不影响解题,因为输出的结果确实是按照二叉查找树的性质来输出的。比如测试用例是[1,2,3],k = 1
正确的BST应该是
2 / \ 1 3
返回的结果是1。
但是测试用例建立的树却是
1 / \ 2 3
返回的结果是2。
虽然它的树建错了,但是根据BST,根节点的值大于左子节点的值,而小于右子节点的值,所以上述例子中第1小的元素是在左子节点,因此输出是2。
接下来说一下我的思路。BST的性质上面讲了,就是左子节点< 根节点 < 右子节点。所以如果对BST进行中序遍历,就会得到一个有序的数列。这一点很重要,利用这一点,我们可以中序遍历这棵树
4000
(中序非递归遍历请看LeetCode. 94 Binary Tree Inorder Traversal 解题报告), 不同的是我们不输出树的节点值,而是减小k的值,当k=0时,就停止遍历并且返回当前所处节点的值。
通过后看了Discuss,大牛们用的方法就是中序遍历这种方式,所以就不贴他们的解法了,(* ^ __ ^ *) 嘻嘻……
代码
我的代码
/** * 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: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> nodes; TreeNode* pNode = root; while (pNode || !nodes.empty()) { if (pNode) { nodes.push(pNode); pNode = pNode->left; } else { pNode = nodes.top(); nodes.pop(); k--; if (!k) break; pNode = pNode->right; } } return pNode->val; } };
总结
再次复习了一次非递归的中序遍历,只要知道BST的中序遍历得到的是有序的数列,这道题就再没有难度了,稍改一下代码就能通过。这是前天填的坑,现在补回它的解题报告,还有昨天的坑的解题报告会在这两天内补上,一天一坑是不会落下的,只是没时间写解题报告的话会晚点再腾时间写,明天继续加油!
相关文章推荐
- [leetcode] 230. Kth Smallest Element in a BST 解题报告
- LeetCode 230. Kth Smallest Element in a BST 解题报告
- [Leetcode] 230. Kth Smallest Element in a BST 解题报告
- [LeetCode] 230. Kth Smallest Element in a BST 解题思路
- 【LeetCode】230.Kth Smallest Element in a BST(Medium)解题报告
- 【LeetCode】Kth Smallest Element in a BST 解题报告
- LeetCode-Kth Smallest Element in a BST-解题报告
- Leetcode 230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- [LeetCode] 230. Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
- LeetCode#230. Kth Smallest Element in a BST
- [Leetcode] 230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST-递归|非递归
- 230. Kth Smallest Element in a BST LeetCode
- 【LeetCode】230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST
- [leetcode] 230. Kth Smallest Element in a BST
- [LEETCODE]230. Kth Smallest Element in a BST