Thursday, August 6, 2015

114 - 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

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.
Hide Tags
Tree Depth-first Search

前序遍历,把左边的挂在右边,左边置空,右边的挂在左边的返回位置的右边。
记得先把右边的 child 保存一下,不然处理右边的时候就出问题了。

/**
* Definition for a binary tree node.
* 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)
            build(root, root);
    }
   
    TreeNode* build(TreeNode* node, TreeNode*& newlink)
    {
        newlink = node;
       
        if((NULL == node->left) && (NULL == node->right))
            return node;
           
        TreeNode* last = node;
        TreeNode* rrrr = node->right;
        if(node->left)
            last = build(node->left, node->right);
        node->left = NULL;       
        if(rrrr)
            last = build(rrrr, last->right);
        return last;
    }
};


8 ms.

No comments:

Post a Comment