二叉树的遍历(更新中)

来源:互联网 发布:网红拍照软件 编辑:程序博客网 时间:2024/05/22 00:31

本文记录二叉树的几种遍历方式,包括:前序,中序,后序三种遍历方式的递归与非递归实现以及层次遍历。

前序:根,左,右;

中序:左,根,右;

后序:左,右,根;

层次:按层从左到右。

/* define of binary treetypedef struct Tree{    int value;    Tree *left, *right;}*BinaryTree;*/

1, 前序遍历:

非递归实现:

typedef struct Node{      BinaryTree index;       int flag; //记录栈中每个元素的状态:0表示还未遍历该节点的左子树,1表示已经遍历了左子树。  };void inorderTraversal(TreeNode *root) {if(root == NULL) return;stack<Node>st;Node n;n.pointer = root;n.flag = 0;st.push(n);while(!st.empty()){Node top = st.top();if(top.flag == 0){st.top().flag = 1;if(top.pointer->left != NULL){Node tmp;tmp.pointer = top.pointer->left;tmp.flag = 0;st.push(tmp);}}else{st.pop();cout<<top.pointer->value<<endl; //visitif(top.pointer->right != NULL){Node tmp;tmp.pointer = top.pointer->right;tmp.flag = 0;st.push(tmp);}}}}


2, 中序遍历:

3, 后序遍历:

递归实现:

void postOrder(BinaryTree root){if(root == NULL) return;postOrder(root->left);postOrder(root->right);printf("%d ", root->value);}

非递归实现:

typedef struct Node{    BinaryTree index;     int flag; //记录栈中每个元素的状态:0表示还未遍历该节点的左右子树,1表示已经遍历了左子树还未遍历右子树,2表示已经遍历完了左右子树。};void postorder_no_re(BinaryTree root){    if(root == NULL) return;    stack<Node>st;    Node tmp;    tmp.index = root;    tmp.flag = 0;    st.push(tmp);        while(!st.empty())    {        Node top = st.top();        if(top.flag == 2) //当左右子树都已遍历完成,现在就该遍历当前节点        {            printf("%d ", top.index->value);            st.pop();        }        else if(top.flag == 0) //需要遍历左子树        {            st.top().flag = 1;            BinaryTree left = top.index->left;            if(left != NULL)             {                Node node;                node.index = left;                node.flag = 0;                st.push(node);            }        }        else  // 遍历右子树        {            st.top().flag = 2;            BinaryTree right = top.index->right;            if(right != NULL)            {                Node node;                node.index = right;                node.flag = 0;                st.push(node);            }        }    }}

4, 层次遍历:




原创粉丝点击