Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6对了,做这道题的时候发现一个小问题:unsigned int a=0,这个时候如果用a-1的话会得到一个大整数,不是-1,会导致循环出问题。
class Solution {
public:
void flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<TreeNode*> path;
_preorder(root,path);
int length=path.size();
for(int i=0 ; i<length-1 ; i++){
path[i]->right=path[i+1];
path[i]->left=NULL;
}
}
void _preorder(TreeNode *root, vector<TreeNode*>& path){
if(root==NULL)
return;
path.push_back(root);
if(root->left)
_preorder(root->left,path);
if(root->right)
_preorder(root->right,path);
}
};