Flatten Binary Tree to Linked List

 

Q:

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
Hints:

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

A:

就是前序遍历,栈中保存右节点,注意在弹栈之前将新形成的树的右节点置为栈顶元素。

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<TreeNode*> s;
        TreeNode* cur = root;
        TreeNode* pre = NULL;
        while(cur || !s.empty()) {
            while (cur) {
                if (cur->right) s.push(cur->right);
                TreeNode* tmp = cur->left;
                cur->left = NULL;
                cur->right = tmp;
                pre = cur;
                cur = tmp;
            }
            
            if (!s.empty()) {
                cur = s.top();
                if (pre) pre->right = cur;
                s.pop();
            }
        }
    }
};

 

posted @ 2013-07-03 00:10  dmthinker  阅读(124)  评论(0)    收藏  举报