# [Leetcode]Flatten Binary Tree to Linked List~

170人阅读 评论(0)

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 上张图记录下，这种感觉蛮好的

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：31468次
• 积分：1077
• 等级：
• 排名：千里之外
• 原创：78篇
• 转载：10篇
• 译文：1篇
• 评论：7条
文章分类
阅读排行
评论排行
最新评论