Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
789 B
2
Indexable
Never
void inorder(TreeNode<int>* root,vector<int> &ino){
    if ( root == NULL )
        return;
    
    inorder(root -> left,ino);
    ino.push_back(root->data);
    inorder(root -> right,ino);
}

TreeNode<int>* flatten(TreeNode<int>* root)
{
    if( root == NULL || !root -> left && !root -> right)
        return root;
    
    vector<int> path;
    inorder(root,path);
    
    TreeNode<int>* newRoot = new TreeNode<int>(path[0]);
    TreeNode<int>* curr = newRoot;
    
    for(int i=1; i<path.size(); i++){
        TreeNode<int>* temp = new TreeNode<int>(path[i]);
        
        curr -> left = NULL;
        curr -> right = temp;
        curr = temp;
    }
    
    curr -> right = NULL;
    curr -> left  = NULL;
    
    return newRoot;
    
    
}