leetcode 114 二叉树展开为链表

简介

先进行中序遍历然后, 对指针进行迁移, 顺便对节点数据进行迁移.

code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> v;
    vector<TreeNode *> vd;
    unordered_map<TreeNode *, bool> m;
    void DLR(TreeNode * r){
        if(r != nullptr){
            v.push_back(r->val);
            vd.push_back(r);
            DLR(r->left);
            DLR(r->right);
        }
    }
    void flatten(TreeNode* root) {
        DLR(root);
        if(root == nullptr) return;
        for(int i=0; i<vd.size() - 1; i++) {
            vd[i]->left = nullptr;
            vd[i]->right = vd[i+1];
            vd[i]->val = v[i];
        }
        return;
    }
};
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14842965.html