一.题目描述
将一棵二叉树按照前序遍历拆解成为一个假链表
。所谓的假链表是说,用二叉树的 right指针,来表示链表中的 next 指针。
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出
样例
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
挑战
不使用额外的空间耗费。
二.解题思路
先用递归的方法将左子树和右子树都变成假链表,再找到左子树的最后一个节点,令根节点的左子树为空,右子树等于左子树,再令左子树的最后一个节点的左子树为空,右子树等于根节点的右子树.
三.实现代码
/**
* 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: nothing
*/
void flatten(TreeNode *root) {
// write your code here
if(root==NULL) return;
TreeNode *left=root->left;
TreeNode *right=root->right;
TreeNode *p=new TreeNode;
flatten(left);
flatten(right);
if(left!=NULL)
{ p=left;
while(p->right!=NULL)
{ p=p->right;}
root->left=NULL;
root->right=left;
p->left=NULL;
p->right=right;
}
}
};
四.感悟
/**
* 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: nothing
*/
void flatten(TreeNode *root) {
// write your code here
if(root==NULL) return;
TreeNode *left=root->left;
TreeNode *right=root->right;
TreeNode *p=new TreeNode;
flatten(left);
flatten(right);
if(left!=NULL)
{ p=left;
while(p->right!=NULL)
{ p=p->right;}
root->left=NULL;
root->right=left;
p->left=NULL;
p->right=right;
}
}
};
这道题的难点在于如何将左子树和右子树连起来,需要找到左子树的最后一个节点,将其与右子树的第一个节点连在一起.