标签:
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?
Hint:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int res = 0; public int counter = 0; public int kthSmallest(TreeNode root, int k) { inOrderK(root, k); return res; } public void inOrderK(TreeNode root, int k){ if(root.left!=null) inOrderK(root.left, k); counter++; if(counter == k) { res = root.val; return; } if(root.right!=null) inOrderK(root.right, k); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode Kth Smallest Element in a BST
标签:
原文地址:http://blog.csdn.net/yangliuy/article/details/46954867