二叉树
方法二:
1 #include<iostream> 2 using namespace std; 3 4 struct BTNode 5 { 6 7 char data; 8 BTNode *left, *right; 9 BTNode(char val) : data(val), left(NULL), right(NULL) {} 10 ~BTNode() 11 { 12 delete left; 13 delete right; 14 } 15 }; 16 17 void CreateBTree(BTNode *&root) 18 { 19 char ch; //要插入的数据 20 cin >> ch; 21 if (ch == '#') 22 root = NULL; 23 else 24 { 25 root = new BTNode(ch); 26 printf("请输入%c的左孩子:", ch); 27 CreateBTree(root->left); 28 printf("请输入%c的右孩子:", ch); 29 CreateBTree(root->right); 30 } 31 } 32 33 int main() 34 { 35 BTNode *root; 36 return 0; 37 }
1 #include<iostream> 2 using namespace std; 3 4 struct BTNode 5 { 6 7 char data; 8 BTNode *left, *right; 9 BTNode(char val) : data(val), left(NULL), right(NULL) {} 10 ~BTNode() 11 { 12 delete left; 13 delete right; 14 } 15 }; 16 17 void CreateBTree(BTNode *&root) 18 { 19 char ch; //要插入的数据 20 cin >> ch; 21 if (ch == '#') 22 root = NULL; 23 else 24 { 25 root = new BTNode(ch); 26 root->data = ch; 27 printf("请输入%c的左孩子:", ch); 28 CreateBTree(root->left); 29 printf("请输入%c的右孩子:", ch); 30 CreateBTree(root->right); 31 } 32 } 33 34 int main() 35 { 36 BTNode *root; 37 return 0; 38 }
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 *l,TreeNode *r):val(x),left(l),right(r){}
};
TreeNode *RebuildTree(string s){
//第一步,字符串转数组
stringstream ss;
ss<<s.substr(1,s.size()-2);//去除头尾的[]后输入ss
string tmp;
vector<TreeNode *> v_node;
while (getline(ss,tmp,',')){
if(tmp == "null")
v_node.push_back(nullptr);
else
v_node.push_back(new TreeNode(stoi(tmp)));
}
int length = v_node.size();
//第二步,判断数组长度是否满足完整的二叉树长度
//部分输入会省略掉尾部的null节点,需要补足才能正常生成
int x = 0;
while(x<length){
x = (x<<1)|1;
}
length = x;
for(int i=length;i<x;++i)
v_node.push_back(nullptr);
//第三步,二叉树生成,因为节点已经在上面申请了,此处只需要指向即可
TreeNode *root = nullptr;
if(length)
root = v_node[0];
for(int i=0;i<length/2;i++){
TreeNode *p = v_node[i];
p->left = v_node[2*i+1];
p->right = v_node[2*i+2];
}
return root;
}