二叉树前中后、层次遍历

#include<iostream>
#include<stack>
#include<queue>
using namespace std;

/*
二叉树遍历算法递归+非递归:
前序遍历:根->左->右
中序遍历:左->根->右
后序遍历:左->右->根
层次遍历
*/
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x): val(x),left(NULL),right(NULL) {}
};

/*递归版本*/
void prerecusive(TreeNode *root)
{
    if (!root) return;
    cout << root->val << " ";
    prerecusive(root->left);
    prerecusive(root->right);
}
void inrecusive(TreeNode *root)
{
    if (!root) return;
    inrecusive(root->left);
    cout << root->val << " ";
    inrecusive(root->right);
}
void postrecusive(TreeNode *root)
{
    if (!root) return;
    postrecusive(root->left);
    postrecusive(root->right);
    cout << root->val << " ";
}

/*循环版本。栈做辅助*/
void preiteration(TreeNode *root)
{
    if (!root) return;
    stack<TreeNode *> s;
    s.push(root);
    while (!s.empty())
    {
     TreeNode *curr=s.top(); cout
<< curr->val << " "; s.pop(); if (curr->right) s.push(curr->right); if (curr->left) s.push(curr->left); } } void initeration(TreeNode *root) { if (!root) return; stack<TreeNode *> s; TreeNode *curr = root; while (curr || !s.empty())//s没有值,第一个判断条件是curr不是空 { if (curr) { s.push(curr); curr = curr->left; } else { cout << s.top()->val << " "; curr = s.top()->right; s.pop(); } } } void postiteration(TreeNode *root) { if (!root) return; stack<TreeNode *> s; s.push(root); TreeNode *curr; TreeNode *visited;//记录子节点已经访问过 while (!s.empty()) { curr = s.top(); /* * 出栈条件: * 对于叶子节点:直接弹出 * 对于非叶子节点:如果已经遍历过其左子节点或右子节点,则弹出 */ if ((!curr->left && !curr->right) || (visited && (curr->left==visited || curr->right == visited))) { cout << curr->val << " "; visited = curr; s.pop(); } else { if (curr->right) s.push(curr->right); if (curr->left) s.push(curr->left); } } } void leveltraverse(TreeNode *root) { if (!root) return; queue<TreeNode *> q; TreeNode *curr; q.push(root); while (!q.empty()) { curr = q.front(); cout << curr->val << " "; q.pop(); if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); } }
原文地址:https://www.cnblogs.com/beixiaobei/p/10914253.html