LeetCode题解: Flatten Binary Tree to Linked List

来源:互联网 发布:会员制软件 编辑:程序博客网 时间:2024/06/05 20:51

Flatten Binary Tree to Linked List

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

思路:

按preorder顺序访问树,使用迭代的方式进行。这样迭代过程中下一个结点就是当前结点的右子树,而设置当前结点的左子树为空,最后形成目标链表。

题解:

/** * Definition for binary tree * 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 == nullptr)            return;                list<TreeNode*> q;        q.push_back(root);        while(! q.empty())        {            TreeNode* t  = q.front();            q.pop_front();                        if (t->right) q.push_front(t->right);            if (t->left) q.push_front(t->left);                        t->left = nullptr;            t->right = q.empty() ? nullptr : q.front();        }                return;    }};


原创粉丝点击