Advertisement
i_love_rao_khushboo

114. Flatten Binary Tree to Linked List

Apr 1st, 2022
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.    
  15.     void preorder(TreeNode *root, vector<int> &pre) {
  16.         if(root == NULL) return;
  17.         pre.push_back(root->val);
  18.         preorder(root->left, pre);
  19.         preorder(root->right, pre);
  20.     }
  21.    
  22.     void flatten(TreeNode* root) {
  23.         if(root == NULL) return;
  24.        
  25.         vector<int> pre;
  26.         preorder(root, pre);
  27.        
  28.         TreeNode *cur = root;
  29.        
  30.         for(int i = 0; i < pre.size(); i++) {
  31.             cur->val = pre[i];
  32.             cur->left = NULL;
  33.            
  34.             if(cur->right) cur = cur->right;
  35.             else {
  36.                 if(i == pre.size() - 1) continue;
  37.                 TreeNode *new_node = new TreeNode();
  38.                 cur->right = new_node;
  39.                 cur = cur->right;
  40.             }
  41.         }
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement