Flatten Binary Tree to Linked List [LeetCode]

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.

Solution:

 1     void flatten(TreeNode *root) {
 2         stack<TreeNode *> nodes;
 3         if(root == NULL)
 4             return;
 5         nodes.push(root);
 6         TreeNode * pre = root;
 7         while(nodes.size() != 0){
 8             TreeNode * node = nodes.top();
 9             nodes.pop();
10             if(node->right != NULL)
11                 nodes.push( node->right);
12             if(node->left != NULL)
13                 nodes.push( node->left);
14             pre->left = NULL;
15             if(node != root){
16                 pre->right = node;
17                 pre = pre->right;
18             }
19                 
20         }
21     }

 

posted @ 2013-11-27 15:15  假日笛声  阅读(206)  评论(0编辑  收藏  举报