【LeetCode】230.Kth Smallest Element in a BST(Medium)解题报告
2018-03-11 10:11
543 查看
【LeetCode】230.Kth Smallest Element in a BST(Medium)解题报告
题目地址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
题目描述:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Solution:
Date:2018年3月11日
题目地址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
题目描述:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Solution:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } 二叉搜索树是一个递增的序列 time : O(n) space : O(n) */ class Solution { private static int count = 0; private static int res = 0; public int kthSmallest(TreeNode root, int k) { count = k; helper(root); return res; } public void helper(TreeNode root){ if(root==null) return; helper(root.left); count--; if(count==0){ res = root.val; } helper(root.right); } }
Date:2018年3月11日
相关文章推荐
- (medium)LeetCode 230.Kth Smallest Element in a BST
- LeetCode 230. 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 解题报告
- LeetCode-Kth Smallest Element in a BST-解题报告
- 230.leetcode Kth Smallest Element in a BST(medium)[二叉搜索树 先序遍历 栈]
- [Leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告
- [Leetcode 230, Medium] Kth Smallest Element in a BST
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告
- leetcode230:Kth Smallest Element in a BST(medium)
- [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 378. Kth Smallest Element in a Sorted Matrix 解题报告
- leetCode 230.Kth Smallest Element in a BST
- Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)
- [LeetCode]Kth Smallest Element in a BST
- #leetcode#Kth Smallest Element in a BST