题目描述:
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/
2 5
/ \
3 4 6
将其展开为:
1
2
3
4
5
6
思路:
先把左树展开为链表、右树展开为链表
然后再把左树加到右边
步骤:
1、把左右树都变成链表
2、然后保存右树,把左树接到右树
3、左树置空
4、找到右树的最右的节点,把之前保存的右树接进去
代码入下:
C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->left);
flatten(root->right);
TreeNode* temp=root->right;
root->right=root->left;
root->left=NULL;
while(root->right){
root=root->right;
}
root->right=temp;
}
};
python:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:return
self.flatten(root.left)
self.flatten(root.right)
temp=root.right
root.right=root.left
root.left=None
while root.right:
root=root.right
root.right=temp