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
此題看題目給出的示例就知道是先序遍歷
本題用遞迴求先序遍歷
class Solution { public: vector<TreeNode *> res; void preTraverse(TreeNode *root){ if(root == NULL) return; res.push_back(root); preTraverse(root->left); preTraverse(root->right); } void flatten(TreeNode *root) { if(root == NULL) return; preTraverse(root); for(int i = 1 ; i < res.size(); ++ i){ res[i-1]->left =NULL; res[i-1]->right = res[i]; } res[res.size()-1]->left =NULL; res[res.size()-1]->right = NULL; } };
下面用迭代求解,一步步的構造結點,由於題目是先序遍歷,可以將右子樹連結到左子樹最右的孩子結點,如果不明白的可以手動模擬一下看與先序遍歷是否相同,然後從根結點一步步往下構造
class Solution { public: void flatten(TreeNode *root) { if(root == NULL) return; while(root){ if(root->left){ TreeNode* ptr = root->left; while(ptr->right) ptr = ptr->right; ptr->right = root->right; root->right = root->left; root->left = NULL; } root = root->right; } } };