首页 > 代码库 > LeetCode: Flatten Binary Tree to Linked List [114]

LeetCode: Flatten Binary Tree to Linked List [114]

【题目】


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.




【题意】

    将一颗二叉树转化为链表,right充当next指针,元素顺序为先序遍历的循序。不使用额外的空间


【思路】


    先对左子树链表化,然后将右子树链表化。然后按照:根节点->左子树链表->右子树链表 的顺序组合成完整的链表


【代码】

/**
 * 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* flattenTree(TreeNode *root){
        if(root->left==NULL && root->right==NULL)return root;
        TreeNode*tail=root;
        TreeNode*headLeft=root->left;
        TreeNode*tailLeft=NULL;
        TreeNode*headRight=root->right;
        TreeNode*tailRight=NULL;
        //【注意】左孩子清NULL
        root->left=NULL;
        //将左子树链表化
        if(headLeft!=NULL){
            tailLeft=flattenTree(headLeft);
            tail->right=headLeft;
            tail=tailLeft;
        }
        //将右子树链表化
        if(headRight!=NULL){
            tailRight=flattenTree(headRight);
            tail->right=headRight;
            tail=tailRight;
        }
        return tail;
    }
    
    void flatten(TreeNode *root) {
        if(root==NULL)return;
        flattenTree(root);
    }
};