C++實(shí)現(xiàn)LeetCode(173.二叉搜索樹(shù)迭代器)
[LeetCode] 173.Binary Search Tree Iterator 二叉搜索樹(shù)迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
這道題主要就是考二叉樹(shù)的中序遍歷的非遞歸形式,需要額外定義一個(gè)棧來(lái)輔助,二叉搜索樹(shù)的建樹(shù)規(guī)則就是左<根<右,用中序遍歷即可從小到大取出所有節(jié)點(diǎn)。代碼如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
while (root) {
s.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *n = s.top();
s.pop();
int res = n->val;
if (n->right) {
n = n->right;
while (n) {
s.push(n);
n = n->left;
}
}
return res;
}
private:
stack<TreeNode*> s;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
- C++數(shù)據(jù)結(jié)構(gòu)二叉搜索樹(shù)的實(shí)現(xiàn)應(yīng)用與分析
- C++實(shí)現(xiàn)LeetCode(109.將有序鏈表轉(zhuǎn)為二叉搜索樹(shù))
- C++實(shí)現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹(shù))
- C++實(shí)現(xiàn)LeetCode(99.復(fù)原二叉搜索樹(shù))
- C++實(shí)現(xiàn)LeetCode(98.驗(yàn)證二叉搜索樹(shù))
- C++實(shí)現(xiàn)LeetCode(96.獨(dú)一無(wú)二的二叉搜索樹(shù))
- C++實(shí)現(xiàn)LeetCode(95.獨(dú)一無(wú)二的二叉搜索樹(shù)之二)
- C++ 二叉搜索樹(shù)(BST)的實(shí)現(xiàn)方法
- C++ 超詳細(xì)快速掌握二叉搜索樹(shù)
相關(guān)文章
C語(yǔ)言?xún)?nèi)存泄漏常見(jiàn)情況及解決方案詳解
這篇文章主要為大家介紹了C語(yǔ)言?xún)?nèi)存泄漏常見(jiàn)情況及解決方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
C++實(shí)現(xiàn)strcmp字符串比較的深入探討
本篇文章是對(duì)使用C++實(shí)現(xiàn)strcmp字符串比較進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C語(yǔ)言中宏和函數(shù)的9個(gè)區(qū)別詳解
C語(yǔ)言中的宏和函數(shù)是非常相似的,它們都可以完成類(lèi)似的功能。本文為大家整理了C語(yǔ)言中宏和函數(shù)的9個(gè)區(qū)別,感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04
學(xué)習(xí)C語(yǔ)言要掌握的幾個(gè)庫(kù)
本文給大家分享的是網(wǎng)友提出的學(xué)習(xí)C語(yǔ)言要掌握的幾個(gè)庫(kù),這里分享給大家,有需要的小伙伴可以參考下。2015-07-07
C語(yǔ)言代碼實(shí)現(xiàn)點(diǎn)餐系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)點(diǎn)餐系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07

