nikunjsoni

114

Apr 30th, 2021
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 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.     void flatten(TreeNode* root) {
  15.         TreeNode *next = NULL;
  16.         dfs(root, next);
  17.     }
  18.    
  19.     void dfs(TreeNode* &root, TreeNode* &next){
  20.         if(!root) return;
  21.         dfs(root->right, next);
  22.         dfs(root->left, next);
  23.         root->right = next;
  24.         root->left = NULL;
  25.         next = root;
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment