589. N叉树的前序遍历
2024-08-30 14:55:51
【题目】
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
【解析】
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
ret[] #初始化结果数组
if root is None:return [] #树空的情况返回[],所以这里不能return None
#递归时候把该节点加入ret。 root相当于上层的x
#有个问题,每次递归会把ret置空,导致最后ret=[]
ret.append(root.val)
for x in root.children:
#这一步很重要,递归时把每一层的ret元素联合起来
ret.extend(self.preorder(x))
return ret
最新文章
- MySQL实现嵌套集合模型
- SharePoint 2013 状态机工作流之日常报销示例
- CSV的导入导出
- 2016国产恐怖惊悚《诡娃》HD720P.国语中字
- (三)stm32之串口通信DMA传输完成中断
- Binary to Text (ASCII) Conversion
- PPT 制作必备工具
- NFS挂载故障卡死的问题
- JavaScript(7)——事件2.0
- AutoTile 自动拼接(五) 学习与实践
- 添加Action View
- VisualStudio程序运行后控制台窗口一闪就没了
- JNI内存泄露JNI ERROR (app bug): local reference table overflow (max=512)
- linux查看防火墙的状态以及开启关闭
- spring cloud: Hystrix(六):feign的注解@FeignClient:fallbackFactory(类似于断容器)与fallback方法
- 839A Arya and Bran
- OAuth中client id的处理
- Linux内核设计笔记11——定时器
- [LeetCode]22. Generate Parentheses括号生成
- 哈工大LTP