Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * 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 *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- void preorder(TreeNode *root, vector<int> &pre) {
- if(root == NULL) return;
- pre.push_back(root->val);
- preorder(root->left, pre);
- preorder(root->right, pre);
- }
- void flatten(TreeNode* root) {
- if(root == NULL) return;
- vector<int> pre;
- preorder(root, pre);
- TreeNode *cur = root;
- for(int i = 0; i < pre.size(); i++) {
- cur->val = pre[i];
- cur->left = NULL;
- if(cur->right) cur = cur->right;
- else {
- if(i == pre.size() - 1) continue;
- TreeNode *new_node = new TreeNode();
- cur->right = new_node;
- cur = cur->right;
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement