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
1. 递归解法
解题思路:
- 递归遍历,当前结点左子树为空,不需要处理;左子树不为空,寻找左子树的最右节点(该结点是右子树前序遍历下的前继结点),记为temp。temp指向当前结点的右子树的根节点,当前结点的右指针指向自身左子树的根节点,同时将左指针置空。
- 二叉树变换过程
1 / \ 2 5 / \ \ 3 4 6 1 / \ 2 5 \ \ 3 6 \ 4 1 \ 2 \ 3 \ 4 \ 5 \ 6
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->