题目:
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
思路:
思路也很简单:首先分别平坦化左子树和右子树,然后将左子树接在根节点和右子树之间即可。在实现的过程中,一定不能忘记在移动左子树之后,将根节点的左子树指针置位NULL。
代码:
/**
* 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;
}
flatten(root->left);
flatten(root->right);
TreeNode *right = root->right;
root->right = root->left;
root->left = NULL;
while(root->right) {
root = root->right;
}
root->right = right;
}
};