leetcode树之N叉树遍历

N叉树

多叉树的定义:

class TreeNode:
  	def __init__(self, val=None, children=None):
      	self.val = val
        self.children = children

DFS(深度优先遍历)

589、N叉树的前序遍历

给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

示例1:

输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]

示例2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]

代码:

递归:

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        ans = []
        def dfs(root):
            if not root: return
            ans.append(root.val)
            if root.children:
                for child in root.children:
                    dfs(child)
        dfs(root)
        return ans

迭代:

和二叉树的前序遍历迭代一样,先遍历到最左侧叶子结点,然后遍历其兄弟结点直到整个树遍历完成即可

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        stack = []
        ans = []
        cur = root
        # 由于不知道子节点的个数,这里需要记录一下遍历到哪个子节点了
        # 存储的是需要遍历子节点的下一个结点的下标
        cache = {}
        while cur or stack:
          	# 遍历结点至其最左侧叶子结点
            while cur:
                ans.append(cur.val)
                stack.append(cur)
                if not cur.children:
                    break
                cache[cur] = 1
                cur = cur.children[0]
            # 这里注意不能出栈,出栈的条件是子节点为空或者子节点已经遍历完成
            cur = stack[-1]
            # 如果没有叶子结点或者叶子结点已经遍历完,可以将该节点弹出,
            # 将当前结点设置为None,那么下次遍历栈顶就是其父节点
            if not cur.children or cache[cur] > len(cur.children) - 1:
                if cur in cache: del cache[cur]
                stack.pop()
                cur = None
            # 如果存在子节点,那么将其设置为子节点,由于这里cache记录的是下次要遍历的子节点
            # 所以取的是当前值,然后将当前值+1
            else:
                index = cache[cur]
                cache[cur] = index + 1
                cur = cur.children[index]
        return ans
590、N叉树的后序遍历

给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

示例1:

输入:root = [1,null,3,2,4,null,5,6]
输出:[5,6,3,2,4,1]

示例2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]

递归:

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        ans = []
        def dfs(root):
            if not root: return
            if root.children:
                for child in root.children:
                    dfs(child)
            ans.append(root.val)
        dfs(root)
        return ans

迭代:

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if not root: return []
        stack = []
        cur = root
        cache = {}
        ans = []
        while cur or stack:
            while cur:
                stack.append(cur)
                if not cur.children:
                    break
                cache[cur] = 1
                cur = cur.children[0]

            cur = stack[-1]
            # 如果没有子节点或者子节点遍历完成最后将该节点的值加入到结果中
            if not cur.children or cache[cur] > len(cur.children) - 1:
                ans.append(cur.val)
                if cur in cache: del cache[cur]
                stack.pop()
                cur = None
            else:
                index = cache[cur]
                cache[cur] = index + 1
                cur = cur.children[index]
        return ans

BFS(广度优先遍历)

429、N叉树的层序遍历

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

示例1:

输入:root = [1,null,3,2,4,null,5,6]
输出:[[1],[3,2,4],[5,6]]

示例2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]

代码:

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        if not root: return []
        queue = [root]
        ans = []
        while queue:
            n = len(queue)
            level = []
            for i in range(n):
                cur = queue.pop(0)
                level.append(cur.val)
                if cur.children:
                    for child in cur.children:
                        queue.append(child)
            ans.append(level)
        return ans
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

溪语流沙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值