0
点赞
收藏
分享

微信扫一扫

非递归中序遍历二叉树

夕颜合欢落 2022-03-14 阅读 82

void inOrder(BT* root) {
	if (root == NULL)
		return;

	inOrder(root->lchild);

	cout << "Node " << root->num
		<< " 's text is " << root->text << endl;

	inOrder(root->rchild);
}

记录一下中序遍历非递归写法的步骤:

  1. 将树的左边界进栈;
  2. 弹出栈顶元素并打印;
  3. 对弹出元素的右结点重复1、2.

void inOrder_stack(BT* root) {
	if (root == NULL)
		return;

	stack<BT*> in;
	
	//将树的左边界进栈
	while (root != NULL) {
		in.push(root);
		root = root->lchild;
	}

	while (!in.empty()) {
		root = in.top();
		in.pop();

		cout << "Node " << root->num
			<< " 's text is " << root->text << endl;

		root = root->rchild;
		while (root != NULL) {
			in.push(root);
			root = root->lchild;
		}
	}
}
举报

相关推荐

0 条评论