非递归和递归方法遍历二叉树

</pre><p><pre class="cpp" name="code">struct node {
 int value;
 struct node * left;
 struct node * right;
};

void preOrderBTree(struct node * head) {
	if (head == NULL)
		return;
	stack<struct node *> s;
	s.push(head);
	while (!s.empty()) {
		struct node * tmp = s.top();
		cout << tmp->value << " ";
		s.pop();
		if (tmp->right != NULL)
			s.push(tmp->right);
		if (tmp->left != NULL)
			s.push(tmp->left);
	}
	cout << endl;
}
<pre class="cpp" name="code">void circuseBTreePreOrder(struct node * head) {
	if (head == NULL)
		return;
	cout << head->value << " ";
	circuseBTreePreOrder(head->left);
	circuseBTreePreOrder(head->right);
}
void anotherPreOrder(struct node * head) {
	if (head == NULL)
		return;
	stack<struct node *> s;
	s.push(head);
	cout << head->value << " ";
	struct node * tmp = head->left;
	while (1) {
		while (tmp != NULL) {
			s.push(tmp);
			cout << tmp->value << " ";
			tmp = tmp->left;
		}

		if (s.empty())
			break;

		tmp = s.top()->right;
		s.pop();
	}
}


非递归中序遍历二叉树:

void midOrder(struct node * head) {
	if (head == NULL)
		return;

	struct node * tmp = head->left;
	stack<struct node *> s;
	s.push(head);
	while (1) {
		while (tmp != NULL) {
			s.push(tmp);
			tmp = tmp->left;
		}

		if (s.empty())
			break;

		tmp = s.top()->right;
		cout << s.top()->value << " ";
		s.pop();
	}
}

层次遍历二叉树:

void layerOrder(struct node * head) {
	if (head == NULL)
		return;

	queue<struct node *> q;;
	q.push(head);
	while (!q.empty()) {
		struct node * cur = q.front();
		q.pop();
		cout << cur->value << " ";
		if (cur->left != NULL) {
			q.push(cur->left);
		}
		if (cur->right != NULL) {
			q.push(cur->right);
		}
	}
}


非递归后序遍历二叉树:

void postOrder(struct node * head) {
	if (head == NULL)
		return;
	stack<struct node *> s;
	struct node * r = NULL;
	s.push(head);
	struct node * tmp = head->left;
	int flag = 0;

	while (!s.empty()) {
		while (tmp != NULL) {
			s.push(tmp);
			tmp = tmp->left;
		}

		if (s.top() == head) {
			flag++;
		}
		if (flag == 2) {
			cout << s.top()->value << " ";
			break;
		}

		if ((s.top()->right == NULL) || (s.top() == r)) {
			cout << s.top()->value << " ";
			s.pop();
			tmp = NULL;
		}
		else {
			tmp = s.top()->right;
			r = s.top();
		}
	}
}

 

时间复杂度: O(n)

递归的中序遍历和后序遍历方法与文中的前序遍历方法相同,不同的地方就是打印输出的位置。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值