首页 > 代码库 > Leetcode--Flatten Binary Tree to Linked List

Leetcode--Flatten Binary Tree to Linked List

Problem Description:

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.

Hints:

If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.

分析:按照题目的意思,将二叉树变为按先序序列排列的极端右子树形式,因此解题思路就是将二叉树按照先序遍历先把节点保存下来,然后按照要求重建二叉树即可,实际中采用了非递归的先序遍历,将节点保存到vector中,最后将重建二叉树。具体代码如下:

/**
 * 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==NULL)
            return;
        vector<TreeNode *> vec;
        stack<TreeNode *> stk;
        TreeNode *p=root;
        while(p||!stk.empty())
        {
            while(p)
            {
                vec.push_back(p);
                stk.push(p);
                p=p->left;
            }
            if(!stk.empty())
            {
                p=stk.top();
                stk.pop();
                p=p->right;
            }
        }
        root=vec[0];
        for(int i=0;i<vec.size()-1;i++)
        {
            vec[i]->left=NULL;
            vec[i]->right=vec[i+1];
        }
        vec[vec.size()-1]->left=NULL;
        vec[vec.size()-1]->right=NULL;
    }
};