二叉树遍历算法总结(递归+非递归)

二叉树的前序中序后序层序遍历总结(C++版)

 
1、前序遍历(根左右)

递归:没什么好说的

void preOrder(TreeNode* root)
{
    if (!root) return;
    cout << root->val << " ";
    preOrder(root->left);
    preOrder(root->right);
}

 
非递归:借助栈
前序遍历根左右,先将当前节点打印,并将其进栈,节点指向其左孩子,直到左孩子为空。这时相当于左子树已经遍历完了,需要访问右节点,将当前元素指向栈顶元素右孩子,弹出栈顶元素

void preOrder(TreeNode* root)
{
    if (!root) return;
    stack<TreeNode*> s;
    auto cur = root;
    while (cur || s.size())
    {
        while (cur)
        {
            cout << cur->val << " ";
            s.push(cur);
            cur = cur->left;
        }
        auto t = s.top();
        s.pop();
        cur = t->right;
    }
}

 
 
2、中序遍历(左根右)

递归:没什么好说的

void inOrder(TreeNode* root)
{
    if (!root) return;
    inOrder(root->left);
    cout << root->val << " ";
    inOrder(root->right);
}

 
非递归:借助栈
中序遍历左根右,和前序遍历类似,只不过访问节点从第一次进栈时就访问变成出栈时才访问

void inOrder(TreeNode* root)
{
    if (!root) return;
    stack<TreeNode*> s;
    auto cur = root;
    while (cur || s.size())
    {
        while (cur)
        {
            s.push(cur);
            cur = cur->left;
        }
        auto t = s.top();
        s.pop();
        cout << t->val << " ";
        cur = t->right;
    }
}

 
 
3、后序遍历(左右根)

递归:没什么好说的

void postOrder(TreeNode* root)
{
    if (!root) return;
    postOrder(root->left);
    postOrder(root->right);
    cout << root->val << " ";
}

 
非递归:借助栈
后序遍历左右根,反过来是根右左,而我们知道前序遍历是根左右,所以可以首先模拟前序遍历的过程,同时将前序遍历中左右子树遍历过程对换,最后将遍历数组翻转就可以得到后序遍历

void postOrder(TreeNode* root)
{
    if (!root) return;
    stack<TreeNode*> s;
    vector<int> v;
    auto cur = root;
    while (cur || s.size())
    {
        while (cur)
        {
            v.push_back(cur->val);
            s.push(cur);
            cur = cur->right;
        }
        auto t = s.top();
        s.pop();
        cur = t->left;
    }
    reverse(v.begin(), v.end());
    for (auto s : v) cout << s << " ";
}

 
 
4、层序遍历
层序遍历通常借助于队列实现。当根节点不为空时,将根节点入队。当队列不为空时,访问队列头,将队头元素出队,同时将队头元素的非空左右儿子节点依次入队

void bfsTree(TreeNode* root) 
{
    if (!root) return;
    queue<TreeNode*> q;
    q.push(root);
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        cout << t->val << " ";
        if (t->left) q.push(t->left);
        if (t->right) q.push(t->right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值