递归建树(c++)

要点:通过让每一个递归都从数字开始,找到可递归性

struct Tnode {
	int val;
	Tnode* left;
	Tnode* right;
	Tnode(int val = 0, Tnode* left = nullptr, Tnode* right = nullptr)
		:val(val), left(left), right(right) {};
};
class Tree {
private:
	int where;
	bool lflag;
public:
	Tnode* root;
	Tree() {
		root = nullptr;
		lflag = true;
		where = 0;
	}
	void createT_Recursion(string& s, Tnode* r);
};
void Tree::createT_Recursion(string& s, Tnode* r) { //父节点 
	int i = where, n = s.size();
	Tnode* p;
	if (s[i] <= '9' && s[i] >= '0') { //遇到节点,看是根还是子 
		int num = 0;
		while (s[i] <= '9' && s[i] >= '0') {
			num = num * 10 + s[i++] - '0';
		}
		p = new Tnode(num);
		if (r == nullptr) {
			root = p;
			r = p;
		}
		where = i + 1; //下一次继续地方
		if (i == n || s[i] == ')') {
			r->right = p; //该父节点处理完 
			lflag = true;
			return;
		}
		else if (s[i] == '(') { //该节点有子节点 处理所有子节点
			if (r != p ) { //先把该节点挂在当前父节点
				if (lflag) {
					r->left = p;
				}
				else {
					r->right = p;
				}
			}
			lflag = true;
			createT_Recursion(s, p);//该节点作为父节点,建左树
			
			if (s[where] == ')') { //没有右树
				while (where < n && !isdigit(s[where]))
					where++;
				return;
			}
			if (s[where] == ',') { //不能省略
				where++;
			}
			lflag = false; //此时where一定指向数字字符
			createT_Recursion(s, p);
		}
		else if (s[i] == ',') { //父节点的右孩子
			r->left = p;
			lflag = false;
		}
	}
}
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾影林深

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值