1 Orginal problem:
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
2 Solution
using post-order traverse of tree, you can solve it.
The code in C++ as follow:
/**
* 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 ;
flatten(root->left); //先處理左子樹爲鏈表,該語句返回時左子樹已成鏈表
flatten(root->right);//再處理右子樹爲鏈表,該語句返回時右子樹已成鏈表
//最後合併兩個鏈表即可
TreeNode* tmp=root->right;//先備份一下右子樹的根
root->right=root->left;//將左子樹對應的鏈表鏈接在根的右子樹上
TreeNode * tail=root;
for(;tail->right;tail=tail->right);//找到左子樹鏈表的末尾
tail->right=tmp;//將其與右子樹鏈表頭鏈接
root->left=NULL;//最後不要忘了將左子樹置空,如果沒有這句,leetCode 將會提示“double free or corruption (fasttop): 0x0000000002785160 ***”的錯誤
}
};