现在的位置: 首页 > 综合 > 正文

LeetCode题解: Flatten Binary Tree to Linked List

2019年07月24日 ⁄ 综合 ⁄ 共 649字 ⁄ 字号 评论关闭

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;
    }
};

抱歉!评论已关闭.