# Flatten Binary Tree to Linked List

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

# 解题思路：

## 方法一：

/**
* 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:
TreeNode* prenode=NULL;
void preorder(TreeNode* root)
{
if(root)
{
TreeNode* leftnode=root->left;
TreeNode* rightnode=root->right;
if(prenode==NULL)//当这棵新树为空时，我们就将这棵树的根节点定位原树节点
prenode=root;
else
{
prenode->right=root;
prenode->left=NULL;
prenode=root;
}
preorder(leftnode);
preorder(rightnode);

}
}
void flatten(TreeNode* root) {
if(root==NULL) return;
preorder(root);
}
};

## 方法二

eg

class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL) return;
if(root->right==NULL&&root->left==NULL) return;
while(root)
{
if(root->left)
{
TreeNode* le=root->left;
while(le->right)
le=le->right;
le->right=root->right;
root->right=root->left;
root->left=NULL;
}
root=root->right;

}
}
};

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

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