给定一个二叉树的dfs遍历结果(NULL记为*),重构二叉树,返回头节点。
思路:第一遍先把*也插入到树中,第二遍把*改成NULL。
如果直接把*记录为NULL,那再来一个节点就不知道,到底是*赋值的NULL,还是本身自带的NULL。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 struct TreeNode{ 5 char val; 6 TreeNode* left; 7 TreeNode* right; 8 TreeNode(char nval){ 9 val = nval; 10 left = NULL; 11 right = NULL; 12 } 13 }; 14 15 TreeNode* construct(string str){ 16 if(str.empty()) return NULL; 17 18 stack<TreeNode*> temp; 19 TreeNode* root = new TreeNode(str[0]); 20 temp.push(root); 21 22 for(int i=1; i<str.size(); i++){ 23 if( str[i]>=‘a‘ && str[i]<=‘z‘ ){ 24 TreeNode* newNode = new TreeNode(str[i]); 25 while(temp.top()->left && temp.top()->right ) temp.pop(); 26 27 if(temp.top()->left ==NULL) temp.top()->left = newNode; 28 else if(temp.top()->right==NULL ) { 29 temp.top()->right= newNode; 30 } 31 temp.push(newNode); 32 } 33 else if(str[i]==‘*‘){ 34 TreeNode* newNode = new TreeNode(str[i]); 35 if(temp.top()->left ==NULL) temp.top()->left = newNode; 36 else if( temp.top()->right==NULL ){ 37 temp.top()->right = newNode; 38 temp.pop(); 39 } 40 } 41 42 } 43 44 //按层遍历,将*改为NULL 45 queue<TreeNode*> que; 46 TreeNode* cur = NULL; 47 que.push(root); 48 while( !que.empty() ){ 49 int size = que.size(); 50 while(size--){ 51 cur = que.front(); 52 que.pop(); 53 if(cur->left && cur->left->val==‘*‘){ 54 cur->left = NULL; 55 } 56 if(cur->left && cur->left->val!=‘*‘){ 57 que.push(cur->left); 58 } 59 60 if(cur->right && cur->right->val == ‘*‘){ 61 cur->right = NULL; 62 } 63 if(cur->right && cur->right->val !=‘*‘){ 64 que.push(cur->right); 65 } 66 } 67 } 68 69 return root; 70 71 } 72 73 void search(TreeNode* root, string& res){ 74 if(root==NULL){ 75 res+=‘*‘; 76 return; 77 } 78 // res += root->val; 79 search(root->left, res); 80 res += root->val; 81 search(root->right, res); 82 } 83 84 85 int main(){ 86 // string str = "abdm***n**ew**cf**g**"; 87 string str = "ab*gf***c*de**f**"; 88 TreeNode* root = construct(str); 89 90 string out=""; 91 search(root, out); 92 93 cout<<out<<endl; 94 95 }
原文地址:https://www.cnblogs.com/liugl7/p/11286054.html
时间: 2024-10-08 09:01:40