二叉树的非递归中序遍历以及二叉搜索树的迭代器

本文介绍了二叉树的非递归中序遍历算法,通过栈模拟左根右的过程,并应用于二叉搜索树(BST)的迭代器实现,使next()和hasNext()操作在平均O(1)时间内完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树的非递归中序遍历

中序序列为左根右,因此用栈模拟这一过程,就是从当前子树根结点出发,一直往左走,把沿途结点全部入栈,直到最左边,对于最左边的结点来说,他没有左孩子,根据“左根右”的顺序,这时需要从堆栈中弹出这个结点,访问它(这里表现为加到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() and hasNext() 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 when next() 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();
 */

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值