leetcode 二叉树题类型 根据测试用例创建二叉树 方便调试

复制测试用例数据:[1,2,3,null,null,4,5],根据此用例生成二叉树。

代码

#include <iostream>
#include<string>
#include <sstream>
#include<vector>
#include<queue>
using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode() : val(0), left(nullptr), right(nullptr) {}
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
	TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};



//  ************* 输出图形二叉树 *************
void output_impl(TreeNode* n, bool left, string const& indent)
{
	if (n->right)
	{
		output_impl(n->right, false, indent + (left ? "|     " : "      "));
	}
	cout << indent;
	cout << (left ? '\\' : '/');
	cout << "-----";
	cout << n->val << endl;
	if (n->left)
	{
		output_impl(n->left, true, indent + (left ? "      " : "|     "));
	}
}
void output(TreeNode* root)
{
	if (root->right)
	{
		output_impl(root->right, false, "");
	}
	cout << root->val << endl;
	if (root->left)
	{
		output_impl(root->left, true, "");
	}
}
//  ***************************************



TreeNode* initTree(vector<string>& vec)
{
	queue<TreeNode*> qu;
	TreeNode* root = new TreeNode(atoi(vec[0].c_str()));
	int i = 1;
	qu.push(root);
	while (!qu.empty())
	{
		int len = qu.size();
		while (len--)
		{
			TreeNode* node = qu.front();
			qu.pop();
			if (vec[i] != "null")
			{
				node->left = new TreeNode(atoi(vec[i].c_str()));
				qu.push(node->left);
			}
			i++;
			if (i == vec.size())
				return root;
			if (vec[i] != "null")
			{
				node->right = new TreeNode(atoi(vec[i].c_str()));
				qu.push(node->right);
			}
			i++;
			if (i == vec.size())
				return root;
		}
	}
	return root;
}

int main()
{
	vector<string> v;
	string str = "1,2,3,null,null,4,5";   //示例,leetcode上测试用例粘贴此处,删去[]
	stringstream sstr(str);
	string buf;
	while (getline(sstr, buf, ','))
	{
		cout << buf << endl;
		v.push_back(buf);
	}

	TreeNode* root = initTree(v);
	output(root);
	//下面创建solution对象调试代码
}

测试结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值