二叉树的非递归中序遍历
中序序列为左根右,因此用栈模拟这一过程,就是从当前子树根结点出发,一直往左走,把沿途结点全部入栈,直到最左边,对于最左边的结点来说,他没有左孩子,根据“左根右”的顺序,这时需要从堆栈中弹出这个结点,访问它(这里表现为加到res数组中)如果它有右孩子,就往右边走,然后对于这棵子树重复上面的操作。
所以代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
TreeNode* now = root;
while(now || !st.empty()){
while(now){
st.push(now);
now = now->left;
}
if(!st.empty()){
now = st.top();
st.pop();
res.push_back(now->val);
now = now->right;
}
}
return res;
}
};
这个非递归的中序遍历有用的地方在于处理二叉搜索树的迭代器问题上
173. Binary Search Tree Iterator
Medium
1469247FavoriteShare
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.
Example:
BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false
Note:
next()
andhasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.- You may assume that
next()
call will always be valid, that is, there will be at least a next smallest number in the BST whennext()
is called.
我们知道,二叉搜索树的中序遍历一定为升序遍历。所以可以用中序遍历将二叉搜索树变为数组,这样就在O(1)的时间实现next()和hasNext()的操作,但这样的空间复杂度是O(N), 不是O(h)。
利用O(h)的空间复杂度的做法是使用非递归中序遍历,一边遍历,一边使用next和hasNext,这样的空间复杂度就是O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode*> st;
public:
BSTIterator(TreeNode* root) {
TreeNode *p = root;
while (p) {
st.push(p);
p = p -> left;
}
}
/** @return the next smallest number */
int next() {
TreeNode* cur = st.top();
st.pop();
int val = cur->val;
cur = cur->right;
while(cur){
st.push(cur);
cur = cur->left;
}
return val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !st.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/