leetcode--Kth Smallest Element in a BST

来源:互联网 发布:淘宝网怎样和微信绑定 编辑:程序博客网 时间:2024/06/03 14:48

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:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).


题意:在BST树中,查找第k小的节点值

分类:二叉树


解法1:BST树很多问题我们都可以使用中序遍历来解决,这个也不例外

我们设置一个当前访问的元素个数cur,在中序遍历过程中,每要访问一个节点,cur加1

当cur和k相等时,这就是我们要找的节点,返回即可


利用递归来进行中序遍历,如果左子树找不到,则判断是不是当前节点,不是,则在右子树接着找

如果左子树找到了,直接返回

[java] view plain copy
  1. /** 
  2.  * Definition for a binary tree node. 
  3.  * public class TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode left; 
  6.  *     TreeNode right; 
  7.  *     TreeNode(int x) { val = x; } 
  8.  * } 
  9.  */  
  10. public class Solution {  
  11.     public int cur = 0;  
  12.     public int kthSmallest(TreeNode root, int k) {  
  13.         TreeNode res = inorder(root,k);  
  14.         if(res!=nullreturn res.val;  
  15.         return -1;  
  16.     }  
  17.       
  18.     public TreeNode inorder(TreeNode root,int k){  
  19.         if(root==nullreturn null;  
  20.         if(root.left!=null){  
  21.             TreeNode left = inorder(root.left,k);//先在左子树找  
  22.             if(left!=nullreturn left;//如果找到了,返回  
  23.         }  
  24.         cur++;//每次访问节点,都加1  
  25.         if(cur==k) return root;//判断是不是当前节点  
  26.         if(root.right!=null){//最后在右子树找  
  27.             TreeNode right = inorder(root.right,k);  
  28.             if(right!=nullreturn right;  
  29.         }  
  30.         return null;  
  31.     }  
  32. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/47186417

原创粉丝点击