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
相关推荐
用户8356290780513 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780515 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠11 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz31011 小时前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫11 小时前
python环境|conda安装和使用(2)
后端·python
程序员龙叔1 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780511 天前
使用 Python 操作 Word 内容控件
后端·python
LDR0061 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术1 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园1 天前
C++20 Modules 模块详解
java·开发语言·spring