# [Leetcode]Flatten Binary Tree to Linked List~

Flatten Binary Tree to Linked List My Submissions Question
Total Accepted: 66064 Total Submissions: 223714 Difficulty: Medium
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.

Hints:
If you notice carefully in the flattened tree, each node’s right child points to the next node of a pre-order traversal.

Subscribe to see which companies asked this question

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(!root)   return;
if(!root->left && !root->right) return;
flatten(root->left);
flatten(root->right);
if(end(root->left)){
end(root->left) -> right = root->right;
root->right = root->left;
root->left = nullptr;
return;
}
else{
return;
}
}
TreeNode* end(TreeNode* root){
if(!root)   return nullptr;
auto p = root;
while(p->right){
p = p->right;
}
return p;
}
};

P.S 上张图记录下，这种感觉蛮好的

• 本文已收录于以下专栏：

举报原因： 您举报文章：[Leetcode]Flatten Binary Tree to Linked List~ 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)