class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = rightclass Solution: def flatten(self, ...
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.
"""
return self.dfs(root,None)
def dfs(self,root,Node):
if not root : return Node
# 記錄當前遍歷節點的前一個節點
# 首先將右子樹轉換完成,然後將轉換後的鏈表與左子樹最後一層的
# 最右邊的節點
Node = self.dfs(root.right,Node)
Node = self.dfs(root.left,Node)
# 拼接
root.right = Node
root.left = None
return root