二叉树的迭代写法

当然,下面我将为您详细介绍二叉树前序、中序和后序遍历的迭代写法,并附上C++代码示例

  1. 前序遍历的迭代写法:
    前序遍历的非递归写法使用栈来实现。我们首先将根节点入栈,然后进入循环,直到栈为空。在循环中,弹出栈顶节点,访问该节点的值,并将其右子节点(如果存在)入栈,再将左子节点(如果存在)入栈。最后,由于栈是先进后出的结构,所以左子节点会被后弹出,而先访问。

下面是前序遍历的迭代写法的C++代码示例:

void preorder(TreeNode* root)
{
    stack<TreeNode*> my_st;
    if (root == nullptr) return;
    my_st.push(root);
    while(!my_st.empty())
    {
        TreeNode* top = my_st.top();
        my_st.pop();
        cout << " tree node: " << top->val << " ";
        if(top->rightchild != nullptr) my_st.push(top->rightchild);
        if(top->leftchild != nullptr) my_st.push(top->leftchild);
    }
}
  1. 中序遍历的迭代写法:
    中序遍历的非递归写法同样使用栈来实现。我们从根节点开始,首先将根节点和其所有的左子节点依次入栈,直到没有左子节点。然后开始循环,每次从栈中弹出一个节点,访问该节点的值,并将其右子节点(如果存在)入栈。

下面是中序遍历的迭代写法的C++代码示例:

void inorder(TreeNode* root)
{
    stack<TreeNode*> m_st;
    if(root == nullptr) return;
    TreeNode* cur = root;
    while(!m_st.empty() || cur != nullptr)
    {
        if (cur != nullptr){
            m_st.push(cur);
            cur = cur->leftchild;
        }
        else
        {
            TreeNode* tmp = m_st.top();
            m_st.pop();
            cout << "my node : " << tmp->val << " ";
            cur = tmp->rightchild;
        }
    }
}
  1. 后序遍历的迭代写法:
    后序遍历的非递归写法稍微复杂一些,但同样使用栈实现。

下面是后序遍历的迭代写法的C++代码示例:

void postorder(TreeNode* root)
{
    stack<TreeNode*> m_st;
    vector<int> res;
    if (root == nullptr) return;
    m_st.push(root);
    while(!m_st.empty())
    {
        TreeNode* top = m_st.top();
        m_st.pop();
        res.push_back(top->val);
        if (top->leftchild != nullptr) m_st.push(top->leftchild);
        if (top->rightchild != nullptr) m_st.push(top->rightchild);
    }
    cout << "my node:";
    reverse(res.begin(),res.end());
    for(int i = 0; i < res.size(); i++)
    {
       
        cout << res[i] << " " ; 
    }
    cout << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值