LeetCode-114. 二叉树展开为链表

114. 二叉树展开为链表

难度中等468

给定一个二叉树,原地将它展开为一个单链表。

 

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

 

今天在外面跑步,淋了个落汤鸡。

晚上换一家店去吃饭把。

#include 
#include 
#include 
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    void flatten(TreeNode* root) {
        if (root == NULL)
            return;

        queue m_queue;
        backtrace(root, m_queue);

        TreeNode* tmp = root;
        int length = m_queue.size();
        for (int i = 0; i < length; i++) {
            tmp->left = NULL;
            tmp->right = m_queue.front(); 
            tmp = tmp->right;
            m_queue.pop();
        }
        tmp->right = NULL;
    }

private:
    void backtrace(TreeNode *root, queue & m_q) {
        if (root) {
            m_q.push(root);
            if (root->left) {
                backtrace(root->left, m_q);
            }
            if (root->right) {
                backtrace(root->right, m_q);
            }
        }
    }
};

int main() {

    TreeNode* p = new TreeNode(0);
    Solution* ps = new Solution();
    ps->flatten(p);
    while (p) {
        cout << p->val << endl;
        p = p->right;
    }

    return 0;

}

 

你可能感兴趣的:(水题AC记,C++,LeetCode)