Thursday, February 19, 2015

Flatten Binary Tree to Linked List

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

------------------------ thinking ---------------------------------------------------
binary tree pre-order traversal

----------------------- codes ------------------------------------------------------
/**
 * 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;
        stack<TreeNode*> stack;
        if (root->right) {
            stack.push(root->right);
        }
        if (root->left) {
            stack.push(root->left);
        }
        TreeNode *cur = root;
        root->left = NULL;
        while (stack.size()) {
            TreeNode *ele = stack.top();
            stack.pop();
            if (ele->right) {
                stack.push(ele->right);
            }
            if (ele->left) {
                stack.push(ele->left);
            }
            ele->left = NULL;
            ele->right = NULL;
            cur->right = ele;
            cur = ele;
        }
        return;
    }
};

No comments:

Post a Comment