fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct TreeNode{
  5. int val;
  6. vector<TreeNode*>child;
  7. TreeNode(int val):child({}),val(val){};
  8. };
  9.  
  10. TreeNode* construct(vector<int>&arr){
  11. stack<TreeNode*>st;
  12. TreeNode* root;
  13. if(arr[0]!=-1){
  14. root = new TreeNode(arr[0]);
  15.  
  16. }
  17.  
  18.  
  19.  
  20. st.push(root);
  21. //potentially wrong :
  22. //did not handle popping for -1 val
  23. //root->children should be attached to the last st val
  24. for(int i = 1;i<arr.size();i++){
  25. if(arr[i]!=-1){
  26. TreeNode* par = st.top();
  27. TreeNode* newChild= new TreeNode(arr[i]);
  28. par->child.push_back(newChild);
  29. st.push(newChild);
  30. }else{
  31. st.pop();
  32. }
  33. }
  34. return root;
  35. }
  36. void display(TreeNode* root){
  37. //pw
  38. if(root!=NULL){
  39. cout<<root->val<<"->";
  40. }
  41.  
  42. //
  43. for(TreeNode* child : root->child){
  44. //TreeNode* child=root->child[i];
  45. cout<<child->val<<",";
  46. }
  47.  
  48. cout<<"."<<endl;
  49.  
  50. for(TreeNode* child:root->child){
  51. display(child);
  52. }
  53. }
  54. int main() {
  55. vector<int>arr = {10,20,50,-1,60,-1,-1,30,70,-1,80,100,-1,110,-1,-1,90,-1,-1,40,120,-1,130,-1,-1,-1};
  56. TreeNode* root = construct(arr);
  57. display(root);
  58. return 0;
  59. }
Success #stdin #stdout 0s 5300KB
stdin
Standard input is empty
stdout
10->20,30,40,.
20->50,60,.
50->.
60->.
30->70,80,90,.
70->.
80->100,110,.
100->.
110->.
90->.
40->120,130,.
120->.
130->.