问题:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
分析:
这道题个人感觉有点奇怪,不是很懂它的题意到底是要干什么。没说明要怎么捋平呀,后面参考
https://www.cnblogs.com/nashiyue/p/5313767.html
大意就是需要一个递归操作的过程:
对当前节点,如果它有左孩子,则找到它左孩子的最右子节点,将当前节点的右子树(不管有没有)接在最右子节点上,然后再将当前节点的左孩子接为右孩子,左孩子置为空。然后将当前节点置为它的右孩子。重复以上步骤。
有人知道为什么一定要这样做吗?不能直接重新建一棵树不可以吗?知道的请留下言吧谢谢!
下面上代码:
/**
* 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 == NULL ){
return;
}
//如果有左子节点
if(root->left != NULL) {
TreeNode* cur = root->left;
//找到最右孩子
while(cur->right != NULL ){
cur = cur->right;
}
//替换操作
cur->right = root->right;
root->right = root->left;
root->left = NULL;
}
//切换到当前节点的右孩子继续
flatten(root->right);
}
};