赞
踩
题目描述
给你二叉树的根结点 root
,请你将它展开为一个单链表:
TreeNode
,其中 right
子指针指向链表中下一个结点,而左子指针始终为 null
。示例 1:
输入:root = [1,2,5,3,4,null,6] 输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [0] 输出:[0]
思路
1)先序遍历二叉树到一个list里
2)遍历list,前一个节点为根,后一个节点为右孩子,在置左孩子为None
- # Definition for a binary tree node.
- # class TreeNode(object):
- # def __init__(self, val=0, left=None, right=None):
- # self.val = val
- # self.left = left
- # self.right = right
- class Solution(object):
- def __init__(self):
- self.res = []
- def pretraverse(self, root):
- if not root:
- return None
- self.res.append(root)
- self.pretraverse(root.left)
- self.pretraverse(root.right)
- def flatten(self, root):
- """
- :type root: TreeNode
- :rtype: None Do not return anything, modify root in-place instead.
- """
- self.pretraverse(root)
- for i in range(1, len(self.res)):
- pre,cur = self.res[i-1], self.res[i]
- pre.left = None
- pre.right = cur
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。