114. Flatten Binary Tree to Linked List

来源:互联网 发布:nosql和mysql结合 编辑:程序博客网 时间:2024/04/30 07:43

114 . Flatten Binary Tree to Linked List

Difficulty: Medium

Given a binary tree, flatten it to a linked list in-place.

For example, Given

     1    / \   2   5  / \   \ 3   4   6   The flattened tree should look like:     1  \   2    \     3      \       4        \         5          \           6

解题思路

仔细看看这道题会很快发现,我们其实只要先序遍历整棵树,并且在遍历过程当中将重排问题同步解决就可以了。

在实现过程中,最为麻烦的是将函数尽可能优化,因为要一边搜索一边重排,这就意味着如果没有合理的结构就会有不好的结果。

我在这里使用的就是循环思路,将左子树不断插入到右子树中去即可。中间就是不断遍历左边的树并且一步步让root指向root-〉right即可。

具体实现

/** * 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:    void flatten(TreeNode* root) {        if(root == NULL) return;        while(root)        {            if(root->left)            {                TreeNode *pre = root->left;                while(pre->right)                    pre = pre->right;                pre->right = root->right;                root->right = root->left;                root->left = NULL;            }            root = root->right;        }    }};
0 0