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

分析:实际上是将左子树插到右子树中,因此进行前序遍历,逐一插入即可。

代码如下:

void flatten(TreeNode *root)
    {
        if(root==NULL)return;
        if(root->left!=NULL)
        {
            flatten(root->left);
            TreeNode *tmp=root->left;
            while(tmp->right!=NULL)
            {
                tmp=tmp->right;
            }
            tmp->right=root->right;
            root->right=root->left;
            root->left=NULL;
        }
        if(root->right!=NULL)
        {
            flatten(root->right);
        }
        return;
    }

你可能感兴趣的:(code-tree)