摘要:解題思路本題需要找的是第小的節(jié)點(diǎn)值,而二叉搜索樹的中序遍歷正好是數(shù)值從小到大排序的,那么這題就和中序遍歷一個(gè)情況。
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).
1.解題思路
本題需要找的是第k小的節(jié)點(diǎn)值,而二叉搜索樹的中序遍歷正好是數(shù)值從小到大排序的,那么這題就和中序遍歷一個(gè)情況。
public class Solution { Stacks=new Stack (); public int kthSmallest(TreeNode root, int k) { if(root==null) return 0; pushLeft(root); while(!s.empty()){ TreeNode node=s.pop(); if(--k==0) return node.val; if(node.right!=null) pushLeft(node.right); } return 0; } private void pushLeft(TreeNode root){ TreeNode node=root; while(node!=null){ s.push(node); node=node.left; } } }
3.Follow up
如果樹會(huì)經(jīng)常被更改,為了效率,我們可以對(duì)樹的構(gòu)造稍作變更,添加一個(gè)屬性,來(lái)標(biāo)明該節(jié)點(diǎn)擁有的左子樹的節(jié)點(diǎn)數(shù),而這個(gè)Number就是比當(dāng)前值小的節(jié)點(diǎn)個(gè)數(shù),這樣我們結(jié)合二分法,就很容易找到第k個(gè)小的節(jié)點(diǎn)值。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/69784.html
摘要:中序遍歷復(fù)雜度時(shí)間空間思路因?yàn)樽蠊?jié)點(diǎn)小于根節(jié)點(diǎn)小于右節(jié)點(diǎn),二叉搜索樹的一個(gè)特性就是中序遍歷的結(jié)果就是樹內(nèi)節(jié)點(diǎn)從小到大順序輸出的結(jié)果。這里采用迭代形式,我們就可以在找到第小節(jié)點(diǎn)時(shí)馬上退出。這樣我們就可以用二叉樹搜索的方法來(lái)解決這個(gè)問(wèn)題了。 Kth Smallest Element in a BST Given a binary search tree, write a function...
摘要:題目鏈接二分找結(jié)果,按左邊數(shù)來(lái)分如果改下,加入的,那就可以在時(shí)間內(nèi)找到結(jié)果了 Kth Smallest Element in a BST 題目鏈接:https://leetcode.com/problems... inorder traverse: public class Solution { public int kthSmallest(TreeNode root, int...
摘要:題目意思就是要一個(gè)個(gè)的返回當(dāng)前的最小值。所以解法自然就是。我們需要找出被打亂的點(diǎn)并返回正確結(jié)果。然后將兩個(gè)不正確的點(diǎn)記錄下來(lái),最后回原來(lái)正確的值。如果是葉子節(jié)點(diǎn),或者只有一個(gè)子樹。思想來(lái)自于的代碼實(shí)現(xiàn)。 跳過(guò)總結(jié)請(qǐng)點(diǎn)這里:https://segmentfault.com/a/11... BST最明顯的特點(diǎn)就是root.left.val < root.val < root.right.v...
摘要:先放一行,或一列把堆頂?shù)淖钚≡厝〕鰜?lái),取次,如果該有下一行下一列的,放入堆中最小的個(gè)元素已經(jīng)在上面的循環(huán)被完了,下一個(gè)堆頂元素就是 Problem Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in...
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.Note that it is the kth smallest element in the sorted order, not the...
閱讀 2280·2023-04-26 03:06
閱讀 3697·2023-04-26 01:51
閱讀 2154·2021-11-24 09:38
閱讀 2569·2021-11-17 17:00
閱讀 2421·2021-09-28 09:36
閱讀 1007·2021-09-24 09:47
閱讀 2678·2019-08-30 15:54
閱讀 1621·2019-08-30 15:44