题目链接在此
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
就是把一棵树按先序铺展成一颗斜向右的树。
如果先序遍历一边把值都记下来再建树,那自然是简单。可是怎样用常数空间O(1)来解决呢?
转自这位大神
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* now = root;
while (now) {
if (now->left) {
TreeNode* pre = now->left;
// 找now的左子树的最右子树
while (pre->right) {
pre = pre->right;
}
//把now的右子树,作为【左子树的最右子树】的右子树,
pre->right = now->right;
//把now的左子树,作为now的右子树
now->right = now->left;
now->left = NULL;
}
now = now->right;
}
}
};