114. Flatten Binary Tree to Linked List

来源:互联网 发布:捕风捉影软件 编辑:程序博客网 时间:2024/06/05 13:14

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

click to show hints.

Subscribe to see which companies asked this question

其实这题看了答案也不懂。。。。。

怒抄答案。

class Solution {private:    TreeNode* tail;    public:    void flatten(TreeNode *root) {        if (!root) return;        tail = root;        if (root->left) {            flatten(root->left);            tail->right = root->right;//唯一不懂的是这里。。。tail和root指的不是一个地方?后来觉得可能是全局变量的问题,可能一开始初始化了之后//tail就指向了别的地方?各种不懂。。。。。。            root->right = root->left;            root->left = NULL;        }        flatten(tail->right);    }};
还有一个非递归的版本,更看不懂,微笑脸。

void flatten(TreeNode *root) {while (root) {  if (root->left && root->right) {TreeNode* t = root->left;        while (t->right){  t = t->right;  t->right = root->right;}          if(root->left){root->right = root->left;root->left = NULL;root = root->right;}}



0 0