思路:递归即可

    1. # 给定一个二叉树,原地将它展开为一个单链表。
    2. #
    3. #
    4. #
    5. # 例如,给定二叉树
    6. #
    7. # 1
    8. # / \
    9. # 2 5
    10. # / \ \
    11. # 3 4 6
    12. #
    13. # 将其展开为:
    14. #
    15. # 1
    16. # \
    17. # 2
    18. # \
    19. # 3
    20. # \
    21. # 4
    22. # \
    23. # 5
    24. # \
    25. # 6
    26. # Related Topics 树 深度优先搜索
    27. # 👍 695 👎 0
    28. # leetcode submit region begin(Prohibit modification and deletion)
    29. # Definition for a binary tree node.
    30. # class TreeNode(object):
    31. # def __init__(self, val=0, left=None, right=None):
    32. # self.val = val
    33. # self.left = left
    34. # self.right = right
    35. class Solution(object):
    36. def flatten(self, root):
    37. """
    38. :type root: TreeNode
    39. :rtype: None Do not return anything, modify root in-place instead.
    40. """
    41. def dfs(node):
    42. if not node:
    43. return node
    44. dfs(node.left)
    45. dfs(node.right)
    46. tmp = node.right
    47. node.right = node.left
    48. node.left = None
    49. while node.right:
    50. node = node.right
    51. node.right = tmp
    52. return dfs(root)
    53. # leetcode submit region end(Prohibit modification and deletion)
    54. class TreeNode(object):
    55. def __init__(self, val=0, left=None, right=None):
    56. self.val = val
    57. self.left = left
    58. self.right = right