230. Kth Smallest Element in a BST - Medium
前往題目
之前寫的文章
想法
- 用
priority queue
,取最小的前k
個
思路
仔細觀察會發現這題的數字用inorder
的方式traverse
剛好會排成ascending
的樣子
簡單來說就是,往左邊走就對了,沒有的話就pop
,最後才走右邊
- 借助
stack
的力量 - 只要有左邊的
node
就push
到stack
,然後前往left node
- 如果沒有左邊了就
pop
,然後前往right node
- 沒有
right node
繼續pop
Code
class Solution {
public int kthSmallest(TreeNode root, int k) {
int n = 0; // count
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode currNode = root;
// Start inorder traverse
while (currNode != null || !stack.isEmpty()) {
// inorder
while (currNode != null) {
stack.push(currNode);
currNode = currNode.left;
}
// No more left, begin popping
currNode = stack.pop();
// Add count
n++;
// Reached kth smallest element
if (n == k) return currNode.val;
// No more left, so start looking for the right
currNode = currNode.right;
}
return k;
}
}
230. Kth Smallest Element in a BST - Medium
https://f88083.github.io/2024/04/12/230-Kth-Smallest-Element-in-a-BST-Medium/