首页 > 代码库 > 二叉树遍历 非递归算法

二叉树遍历 非递归算法

mooc的作业本来以为是很简单,真正写下去才知道不简单。

每个都略有技巧,细细琢磨

#include <cstdio>#include <cstring>int all, top;class TreeNode{    public:        int value;        TreeNode* left;        TreeNode* right;        TreeNode(int _value, TreeNode *_left, TreeNode *_right)        {            value = _value;            left = _left;            right = _right;        }};TreeNode *stack[105];int result[105];void preorderTraversal(TreeNode *root, int *result)// 前序遍历{    top = all = 0;    if(root != NULL)        stack[top++] = root;// 根节点入栈    while(top > 0)    {        TreeNode* now = stack[--top];        result[all++] = now->value;        if(now -> right != NULL)            stack[top++] = now->right;// 插入右节点        if(now -> left != NULL)            stack[top++] = now->left;// 插入左节点    }}void inorderTraversal(TreeNode *root, int *result)// 中序遍历{    top = all = 0;    TreeNode* now = root;    while(1)    {        while(now != NULL)// 先到最左边的儿子         {            stack[top++] = now;// 父节点入栈            now = now->left;        }        if(top == 0) break;        now = stack[--top];// 若无右儿子取父亲        result[all++] = now->value;        now = now->right;// 先右儿子    }}void postorderTraversal(TreeNode *root, int *result)// 后序遍历{    top = all = 0;    TreeNode* now = root;    while(1)    {        while(now->left != NULL || now->right != NULL)// 找出下一个节点        {            stack[top++] = now; // 当前节点入栈            if(now->left != NULL)            {                now = now->left;                stack[top-1]->left = NULL;// 删除父亲节点的左儿子            }            else            {                now = now->right;                stack[top-1]->right = NULL;// 删除父亲节点的右儿子            }        }        result[all++] = now->value;        if(top == 0) break;        now = stack[--top];    }}int main(){/*        0        /        1 5       /\         2 3  6        /        4*//*        TreeNode* t6 = new TreeNode(6, NULL, NULL);    TreeNode* t5 = new TreeNode(5, NULL, t6);    TreeNode* t4 = new TreeNode(4, NULL, NULL);    TreeNode* t3 = new TreeNode(3, t4, NULL);    TreeNode* t2 = new TreeNode(2, NULL, NULL);    TreeNode* t1 = new TreeNode(1, t2, t3);    TreeNode* t0 = new TreeNode(0, t1, t5);    preorderTraversal(t0, result);    for(int i = 0; i < all; i++)        printf("%d ", result[i]);    printf("\n");    inorderTraversal(t0, result);    for(int i = 0; i < all; i++)        printf("%d ", result[i]);    printf("\n");    postorderTraversal(t0, result);    for(int i = 0; i < all; i++)        printf("%d ", result[i]);    printf("\n");*/    return 0;}

 

二叉树遍历 非递归算法