欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 114 Flatten Binary Tree to Linked List

程序员文章站 2022-03-07 23:39:56
...

LeetCode 114

Flatten Binary Tree to Linked List

/**
 * Definition for a binary tree node.
 * 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 == NULL) return;
        TreeNode* head = root;
        TreeNode* p = root;
        queue<TreeNode*> tree;
        stack<TreeNode*> node;
        while(p || !node.empty()) {
            while(p) {
                node.push(p);
                tree.push(p);
                p = p->left;
            }
            if (!node.empty()) {
                p = node.top();
                node.pop();
                p = p->right;
            }
        }
        p = head;
        if (!tree.empty())
            tree.pop();
        while(!tree.empty()) {
            TreeNode* q = new TreeNode(tree.front()->val);
            tree.pop();
            p->right = q;
            p->left = NULL;
            p = q;
        }
        p->right = NULL;
        p->left = NULL;
        root = head;
    }
};
相关标签: tree PreOrder