二叉树的遍历(更新中)

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

前序:根,左,右;

中序:左,根,右;

后序:左,右,根;

层次:按层从左到右。

/* define of binary tree
typedef 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; //visit
			if(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, 层次遍历:




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值