非递归构造二叉树

本文探讨了如何在不使用递归的情况下利用栈结构来构建二叉树,详细阐述了非递归构建二叉树的思路和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用递归很容易就能够构造二叉树,但是利用非递归方法就不那么容易。非递归方式构建二叉树需要用到栈的结构,在这里梳理一下思路。

#include <iostream>
#include <stack>
#include <string>

using namespace std;

class BiNode
{
public:
	BiNode() {};
	BiNode(char c) :val(c) {};
	char val;
	BiNode* left = NULL;
	BiNode* right = NULL;
};

BiNode* addTree(string str)
{
	BiNode* root = new BiNode(str[0]);
	stack<BiNode*> stk;
	stk.push(root);
	int id = 1;
	bool A = false;
	while (!stk.empty())
	{
		if (stk.top()->left == NULL && str[id - 1] != '#')
		{
			if (str[id] != '#')
			{
				BiNode* left = new BiNode(str[id]);
				stk.top()->left = left;
				stk.push(left);
			}
			id++;
		}
		else
		{
			if (stk.top()->right == NULL)
			{
				if (str[id] != '#')
				{
					BiNode* right = new BiNode(str[id]);
					stk.top()->right = right;
					stk.push(right);
				}
				else
				{
					stk.pop();
				}
				id++;
			}
			else
			{
				stk.pop();
			}
		}
	}
	return root;
}

void printTree(BiNode* root)
{
	if (root != NULL)
	{
		cout << root->val;
		if (root->left != NULL)
		{
			printTree(root->left);
		}
		if (root->right != NULL)
		{
			printTree(root->right);
		}
	}
}



 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值