思路:递归即可
# 给定一个二叉树,原地将它展开为一个单链表。
#
#
#
# 例如,给定二叉树
#
# 1
# / \
# 2 5
# / \ \
# 3 4 6
#
# 将其展开为:
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Related Topics 树 深度优先搜索
# 👍 695 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# 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 flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
def dfs(node):
if not node:
return node
dfs(node.left)
dfs(node.right)
tmp = node.right
node.right = node.left
node.left = None
while node.right:
node = node.right
node.right = tmp
return dfs(root)
# leetcode submit region end(Prohibit modification and deletion)
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right