[LeetCode] Flatten Tree into Linked List

来源:互联网 发布:数据交互是什么意思 编辑:程序博客网 时间:2024/04/28 06:15

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

Just Simulate Pre-order Traversal


class Solution {public:    void flatten(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        helper(root);           }        TreeNode* helper(TreeNode *root)    {        if(root==NULL) return NULL;                if(root->left==NULL && root->right == NULL)        {            return root;        }                TreeNode* leftlast;        if(root->left != NULL)             leftlast=helper(root->left);        else{            leftlast=NULL;        }               TreeNode* rightlast;        if(root->right !=NULL )             rightlast=helper(root->right);        else{             rightlast=NULL;        }                            if(leftlast!=NULL)         {           if(rightlast!=NULL)           {               leftlast->right=root->right; //root has both left and right child               root->right=root->left;               root->left=NULL;               return rightlast;           }           else           {               root->right=root->left;               root->left=NULL;               return leftlast;//root has no rightchild           }        }        else{            if(rightlast!=NULL)            {                root->left=NULL;                return rightlast; //root has no left child            }            else{                root->left=NULL;                return root; //root is leaf node            }        }            }};

原创粉丝点击