# Flatten Binary Tree to Linked List（medium）

94人阅读 评论(0)

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 binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.peek();
if (top.left != null) {
stack.push(top.left);
top.left = null;
} else if (top.right != null) {
stack.push(top.right);
top.right = null;
} else { //top.left == null && top.right == null
stack.pop();
}
}
TreeNode node = queue.poll();
while (!queue.isEmpty()) {
node.right = queue.poll();
node = node.right;
}
}
}

前序遍历，保存中间变量。

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void helper(TreeNode *root, TreeNode *&pre) {
if (root == NULL) return;
if (pre != NULL) {
pre->left = NULL;
pre->right = root;
}
pre = root;
TreeNode *left = root->left;
TreeNode *right = root->right;
if (left != NULL) {
helper(left, pre);
}
if (right != NULL) {
helper(right, pre);
}
}
void flatten(TreeNode *root) {
TreeNode *pre = NULL;
helper(root, pre);
}
};

    /**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* Tail;
void preOrder(TreeNode* root)
{
if(root != NULL)
{
TreeNode* left = root->left;
TreeNode* right = root->right;
if(Tail == NULL){
Tail = root;
}
else{
if(Tail->right != root)
Tail->right = root;
Tail->left = NULL;
Tail = root;
}
preOrder(left);
preOrder(right);
}
}
void flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
Tail = NULL;
preOrder(root);
}
};  

0
0

个人资料
• 访问：26485次
• 积分：946
• 等级：
• 排名：千里之外
• 原创：58篇
• 转载：70篇
• 译文：1篇
• 评论：1条
阅读排行
最新评论