LeetCode114—Flatten Binary Tree to Linked List

LeetCode114—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

分析

最朴素的方法就是先序遍历把节点保存,然后在顺序构造不含左子树的树,网上看到有其他的方法,等学习研究了再更新。

代码

class Solution {
private:
    void dfs(TreeNode*root, vector&Nodes)
    {
        if (root == NULL)
            return;
        Nodes.push_back(root);
        dfs(root->left, Nodes);
        dfs(root->right, Nodes);
    }
public:
    void flatten(TreeNode* root) {
        if (root == NULL)
            return;
        vectorNodes;
        dfs(root, Nodes);
        int i;
        root->left = NULL;
        for (i = 0; i < Nodes.size() - 1; i++)
        {
            Nodes[i]->right = Nodes[i + 1];
            Nodes[i]->left = NULL;
        }
        Nodes[i]->right = NULL;
        root = Nodes[0];
    }
};

你可能感兴趣的:(leetcode)