首页 > 代码库 > [leetcode]Flatten Binary Tree to Linked List

[leetcode]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

click to show hints.

代码:

void flatten(TreeNode *root) {  //C++
        if(root == NULL)
            return;
        stack<TreeNode* > myStack;
        queue<TreeNode* > myQueue;
        
        TreeNode *p = root;
        while(p!=NULL || !myStack.empty())
        {
            while(p!=NULL){
                myQueue.push(p);
                myStack.push(p);
                p=p->left;
            }
            p = myStack.top();
            myStack.pop();
            p = p->right;
        }
        
        p = myQueue.front();
        myQueue.pop();
        
        while(!myQueue.empty()){
            TreeNode* temp = myQueue.front();
            p->right = temp;
            p->left = NULL;
            p = temp;
            myQueue.pop();
        }
        
    }


[leetcode]Flatten Binary Tree to Linked List