算法描述:
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
解题思路:从题目可以看出,用后续遍历可以解决问题。用一个全局变量存储上一个访问的点,将上一个访问的点挂在右边子树上,并将左边的子树清空。
TreeNode* prev=nullptr; void flatten(TreeNode* root) { if(root==nullptr) return; flatten(root->right); flatten(root->left); root->right = prev; root->left = nullptr; prev = root; }