[leetcode刷题系列]Flatten Binary Tree to Linked List

来源:互联网 发布:福州市网络家长学校 编辑:程序博客网 时间:2024/05/29 17:27

模拟题,不过以前确实没见到过这个类型的题目。 又练习了下指针:)


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    TreeNode * dfs(TreeNode * root){        if(root->left != 0){            TreeNode * last_left = dfs(root->left);            if(root->right == 0){                root->right = root->left;                root->left = 0;                return last_left;            }else{                TreeNode * last_right = dfs(root->right);                last_left->right = root->right;                root->right = root->left;                root->left = 0;                return last_right;            }        }        if(root->right != 0)            return dfs(root->right);        return root;    }public:    void flatten(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == 0)            return ;        dfs(root);    }};