[LeetCode]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
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:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* flat(TreeNode *root)
{
  if(root -> left == NULL)
  {
    if(root -> right == NULL)
    {
      return root;
    }
    else
    {
      return flat(root -> right);
    }
  }
  else
  {
    if(root -> right == NULL)
    {
      root -> right = root -> left;
      root -> left = NULL;
      return flat(root -> right);
    }
    else
    {
      TreeNode *leftEnd = flat(root -> left);
      TreeNode *rightEnd = flat(root -> right);
      TreeNode *tmp = root -> right;
      root -> right = root -> left;
      root -> left = NULL;
      leftEnd -> right = tmp;
      return rightEnd;
    }
  }
    
}

void flatten(TreeNode *root) {
   if(root == NULL) return;
   flat(root);
}
};

 

posted @ 2014-04-24 22:11  xchangcheng  阅读(171)  评论(0编辑  收藏  举报