[LeetCode] flatten binary tree 扁平化二叉树

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.

本题采用递归的方法解决,关键是要知道由左子树转化的链表的头和尾,以及由右子树转化的链表的头和尾。头一定是二叉树的根节点,尾是右子树的尾(如果右子树不空)或者(如果右子树空,左子树不空)或者根(如果左右子树都是空)。

void flatten(TreeNode *root) {
// main function    

    if(root == NULL)
        return;
    ConvertToLink(root);
}


TreeNode* ConvertToLink(TreeNode* root) // utility function
{// return value is the tail of the linked list
    if(root==NULL)
        return NULL;

    TreeNode* leftLinkTail = ConvertToLink(root->left); // tail of left linked list
    TreeNode* rightLinkTail = ConvertToLink(root->right); // tail of left linked list
    
    if(leftLinkTail != NULL)
    {
        leftLinkTail->right = root->right;
        root->right = root->left;
    }
    
    root->left = NULL;

    if(rightLinkTail!= NULL)
        return rightLinkTail;
    else if(leftLinkTail != NULL)
        return leftLinkTail;
    else
        return root;
}




你可能感兴趣的:([LeetCode] flatten binary tree 扁平化二叉树)