12.25-----递归

N 叉树的后序遍历

python 复制代码
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:

        ans=[]
        def dfs_find (root):
            # 终止条件
            if root==None:
                return
            # 保存前序
            
            # 遍历子节点
            for child in root.children:
                # 进入下一层
                dfs_find(child)
            ans.append(root.val)

        dfs_find(root)
        return ans

N 叉树的前序遍历

python 复制代码
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        # 保存结果数组
        ans=[]
        def dfs_find (root):
            # 终止条件
            if root==None:
                return
            # 保存前序
            ans.append(root.val)
            # 遍历子节点
            for child in root.children:
                # 进入下一层
                dfs_find(child)

        dfs_find(root)
        return ans

N 叉树的层序遍历

python 复制代码
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""
    # 广度优先搜索

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: Node
        :rtype: List[List[int]]
        """
        # root 为空返回
        if not root:
            return[]
        ans=list()
        # 队列---root
        q=deque([root])

        # 广度搜索
        while q:
            cnt = len (q)
            # 深度
            level= list()
            for _ in range (cnt):
                cur=q.popleft()
                level.append(cur.val)
                for child in cur.children:
                    q.append(child)
            ans.append(level)
        return ans
相关推荐
梦想的初衷~几秒前
Python驱动的WRF模式自动化:业务化预报系统搭建实战
linux·python·自动化·大气科学·气候环境·风能太阳能
爱玩亚索的程序员2 分钟前
算法入门(一)Python基础(list、dict、set、tuple、for、enumerate、lambda、sorted)
python·算法·list
熙金顺乐葵攘4 分钟前
Web2py Grid 组件实现主从双表联查,卡片订单UI展现、全字段搜索导出的改造
python·web2py
陌雨’7 分钟前
提取b站视频的ai字幕
爬虫·python
cui_ruicheng13 分钟前
C++关联容器进阶:unordered_map / set与详解
开发语言·c++
weipt15 分钟前
FBX转3DTiles带坐标的高效转换工具
python
sycmancia20 分钟前
C++——C++异常处理
开发语言·c++
xxxxxxllllllshi21 分钟前
java值传递和引用传递的区别?举例一些常见都笔试面试题说明,最后有速记口诀
java·开发语言
HLC++24 分钟前
C++中的类和对象
开发语言·c++