题目描述:
Given a binary tree, flatten it to a linked list in-place.把二叉树按前序遍历顺序转化为链表。
思路:遍历二叉树,将左子树插入根节点和右子树之间。
代码:
/**
* 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 flatten(TreeNode *root) {
if(root==NULL){
return;
}
flatten(root->left);
flatten(root->right);
TreeNode *node=root->left;
if(node==NULL){
return;
}
while(node->right){
node=node->right;
}
node->right=root->right;
root->right=root->left;
root->left=NULL;
}
};