文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) {
return;
}
vector<TreeNode*> nodes;
preorderTranverse(nodes, root);
for(int i = 0; i < nodes.size() - 1; i++) {
nodes[i]->left = nullptr;
nodes[i]->right = nodes[i + 1];
}
nodes[nodes.size() - 1]->left = nullptr;
nodes[nodes.size() - 1]->right = nullptr;
}
private:
void preorderTranverse(vector<TreeNode*>& nodes, TreeNode* root) {
if(!root) {
return;
}
nodes.push_back(root);
preorderTranverse(nodes, root->left);
preorderTranverse(nodes, root->right);
}
};