leetcode 114:二叉树展开为链表

二叉树的题,使用递归的方式

TreeNode *last(TreeNode*root){
    while(root->right!=NULL){
        root=root->right;
    }
        return root;

}

TreeNode *fla(TreeNode *root){
    if(root==NULL)
        return NULL;
    if(root->left==NULL&&root->right==NULL)
        return root;
    else if(root->left!=NULL&&root->right!=NULL){
        last(fla(root->left))->right=fla(root->right);
        root->right=NULL;
        root->right=root->left;
        root->left=NULL;
    }
    else if(root->left!=NULL&&root->right==NULL){
        root->right=fla(root->left);
        root->left=NULL;
    }
    else if(root->left==NULL&&root->right!=NULL){
        root->right=fla(root->right);
    }
    return root;
}


void flatten(TreeNode *root) {
      fla(root);
}

猜你喜欢

转载自blog.csdn.net/u013263891/article/details/86566063