Day38: [LeetCode中等] 114. 二叉树展开为链表

Day38: [LeetCode中等] 114. 二叉树展开为链表

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/

代码:

dirty code凑合看吧

/**
 * 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:
    TreeNode* res;
    pair<TreeNode*,TreeNode*> f(TreeNode* root){
        if(!(root->left==NULL&&root->right==NULL)){
            if(root->left!=NULL&&root->right!=NULL){
                pair<TreeNode*,TreeNode*> temp1=f(root->left),temp2=f(root->right);
                root->right=temp1.first;
                root->left=NULL;
                temp1.second->right=temp2.first;
                temp1.second->left=NULL;

                return make_pair(root,temp2.second);
            }else if(root->left==NULL){
                pair<TreeNode*,TreeNode*> temp1=f(root->right);
                root->right=temp1.first;
                root->left=NULL;

                return make_pair(root,temp1.second);
            }else{
                pair<TreeNode*,TreeNode*> temp1=f(root->left);
                root->right=temp1.first;
                root->left=NULL;
                return make_pair(root,temp1.second);
            }
            
        }else return pair<TreeNode*,TreeNode*>(root,root);;
    }
    void flatten(TreeNode* root) {
        if(!root) return;
        f(root);
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 506

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103758419