LeetCode二叉树构造方法,通过一维数组直接构建完整的二叉树(按照LeetCode的格式)

1.LeetCode中二叉树的结构

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

以上是Leetcode中二叉树的结构,然而在题目通常会这样给出

那么从输入一个一维数组如何转变成对应的二叉树结构呢,下面给出源码。

2.从一维数组到对应的二叉树结构

#include<iostream>
#include<vector>
#include<string>
#include<queue>
using namespace std;
#define null 65535
struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) { //结构体的构造函数 
		val = x;
		left = NULL;
		right = NULL;
	}
};
TreeNode* CreateTree(vector<int>Data) {
	vector<string>str_data(Data.size(), "");
	for (int i = 0; i < Data.size(); i++) {
		if (Data[i] != null)
			str_data[i] = to_string(Data[i]);
		else
			str_data[i] = "null";
	}
	queue<TreeNode*>q;
	TreeNode* head = new TreeNode(stoi(str_data[0]));
	q.push(head);
	int i = 1;
	while (i < str_data.size()) {
		TreeNode* tmp = q.front();
		q.pop();
		if (str_data[i] != "null") {
			TreeNode* new_node = new TreeNode(stoi(str_data[i]));
			tmp->left = new_node;
			q.push(new_node);
		}
		i++;
		if (str_data[i] != "null") {
			TreeNode* new_node = new TreeNode(stoi(str_data[i]));
			tmp->right = new_node;
			q.push(new_node);
		}
		i++;
	}
	return head;
}
void prePrint(TreeNode* Root) {//先序遍历
	if (Root == NULL) return;
	cout << Root->val << ',';
	prePrint(Root->left);
	prePrint(Root->right);
	return;
}
void postPrint(TreeNode* Root) {//后序遍历
	if (Root == NULL) return;
	postPrint(Root->left);
	postPrint(Root->right);
	cout << Root->val << ',';
	return;
}
void inPrint(TreeNode* Root) {//中序遍历
	if (Root == NULL) return;
	inPrint(Root->left);
	cout << Root->val << ',';
	inPrint(Root->right);
	return;
}
int main() {
	vector<int>Data = { 1,2,3,null,4,5,6,7,null };
	TreeNode* Root = NULL;
	Root = CreateTree(Data);
	cout << "PreOrder:" << endl;
	prePrint(Root);
	cout << endl << "InOrder:" << endl;
	inPrint(Root);
	cout << endl << "PostOrder:" << endl;
	postPrint(Root);
	getchar();
}

3.结果验证

测试使用的是上图 所示的二叉树,对应的一维数组是[1,2,3,null,4,5,6,7,null],得到的结果如下:

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

USTC暖暖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值