日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

230.Kth Smallest Element in a BST

發(fā)布時間:2023/12/18 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 230.Kth Smallest Element in a BST 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:

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:

  • Try to utilize the property of a BST.
  • What if you could modify the BST node's structure?
  • The optimal runtime complexity is O(height of BST).
  • 鏈接: ?http://leetcode.com/problems/kth-smallest-element-in-a-bst/

    7/25/2017

    2ms, 20%

    好幾天終于有道自己做的題了。。。iterative inorder traversal

    1 public class Solution { 2 public int kthSmallest(TreeNode root, int k) { 3 Stack<TreeNode> stack = new Stack<>(); 4 TreeNode node = root; 5 int kthSml = 0; 6 7 while((node != null || !stack.isEmpty()) && k > 0) { 8 while (node != null) { 9 stack.push(node); 10 node = node.left; 11 } 12 node = stack.pop(); 13 kthSml = node.val; 14 k--; 15 node = node.right; 16 } 17 return kthSml; 18 } 19 }

    別人的答案

    可以利用DFS求root的count,然后再從左右兩邊找

    https://discuss.leetcode.com/topic/17810/3-ways-implemented-in-java-python-binary-search-in-order-iterative-recursive

    python generator

    https://discuss.leetcode.com/topic/18279/pythonic-approach-with-generator

    更多討論

    https://discuss.leetcode.com/category/238/kth-smallest-element-in-a-bst

    轉載于:https://www.cnblogs.com/panini/p/7236107.html

    總結

    以上是生活随笔為你收集整理的230.Kth Smallest Element in a BST的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。