题目描述:
方法一:迭代
class Solution:def flatten(self, root: TreeNode) -> None:"""Do not return anything, modify root in-place instead."""cur = root while cur: if cur.left: p = cur.left while p.right: p = p.right p.right = cur.right cur.right = cur.left cur.left = None cur = cur.right
方法二:递归
class Solution:def flatten(self, root: TreeNode) -> None:"""Do not return anything, modify root in-place instead."""def helper(root, pre): if not root: return pre # 记录遍历时候,该节点的前一个节点 pre = helper(root.right, pre) pre = helper(root.left, pre) # 拼接 root.right = pre root.left = None pre = root return pre helper(root, None)
如果觉得《leetcode-114-二叉树展开为链表*》对你有帮助,请点赞、收藏,并留下你的观点哦!