Lintcode 453 Splits a binary tree into a linked list, And lintcode into a linked list
Split a binary tree into a linked list
- Description
- Notes
- Data
- Evaluation
Split a binary tree into a binary treeFalse linked list. The so-called false linked list refers to the use of Binary TreesRightPointer to representNextPointer.
Notes
Do not forget to mark the left son as null, otherwise you may get space overflow or time overflow.
Have you ever encountered this question during a real interview? Yes, which company asked you this question? Airbnb Amazon LinkedIn Cryptic Studios Dropbox Epic Systems TinyCo Hedvig Microsoft Yahoo Bloomberg Uber Snapchat Twitter Yelp Apple Google Facebook Zenefits
Thank you for your feedback.
Example
1 \ 1 2 / \ \ 2 5 => 3 / \ \ \ 3 4 6 4 \ 5 \ 6
Challenges
No additional space is required.
The interesting part of this question is to split it into a false linked list of the Right oblique tree, and this question is to traverse and disassemble it according to the forward order, not by the data size.
So it is easy to recursion.
There are two points to think about. Where should we start from? (Pre-order traversal) how to split it? (Save the Left and Right sons)
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /* * @param root: a TreeNode, the root of the binary tree * @return: */ void flatten(TreeNode * root) { // write your code here if(root==NULL) return; TreeNode *l=root->left; TreeNode *r=root->right; flatten(root->left); flatten(root->right); if(root->left==NULL) return ; else { TreeNode *t=root->left; while(t->right) t=t->right; root->left=NULL; root->right=l; t->right=r; } return; }};