【Leetcode每日笔记】114. 二叉树展开为链表(Python)

文章目录

  • 题目
  • 解题思路
    • 前序遍历
    • 寻找前驱节点
  • 代码

题目

给定一个二叉树,原地将它展开为一个单链表。
【Leetcode每日笔记】114. 二叉树展开为链表(Python)_第1张图片

解题思路

前序遍历

递归实现前序遍历

def dfs(root):
	if not root:
		return 
	res.append(root.val)
	dfs(root.left)
	dfs(root.right)

迭代实现前序遍历

cur,stack,res = root,[],[]
while cur or stack:
	while cur:
		stack.append(cur)
		res.append(cur.val)
		cur = cur.left
	tmp = stack.pop()
	cur = tmp.right

寻找前驱节点

【Leetcode每日笔记】114. 二叉树展开为链表(Python)_第2张图片

代码

class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        stack = []
        p = root
        res = []
        while p or stack:
            while p:
                stack.append(p)
                res.append(p.val)
                p = p.left
            tmp = stack.pop()
            p = tmp.right
        res = res[1:]
        while res:
            root.left = None
            root.right = TreeNode(res.pop(0))
            root = root.right
class Solution:
    def flatten(self, root: TreeNode) -> None:
        curr = root
        while curr:
            if curr.left:
                predecessor = nxt = curr.left
                while predecessor.right:
                    predecessor = predecessor.right
                predecessor.right = curr.right
                curr.left = None
                curr.right = nxt
            curr = curr.right

你可能感兴趣的:(LeetCode一周一结,#,树,二叉树,dfs,leetcode,前序遍历,前驱节点)