559. N 叉树的最大深度
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
题解:
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
# if not root.children:
# return 1
return 1 + max((self.maxDepth(ch) for ch in root.children), default = 0)
589. N 叉树的前序遍历
给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
题解:
class Solution(object):
def preorder(self, root):
ans=[]
if not root:
return []
ans+=[root.val]
for child in root.children:
ans+=self.preorder(child)
return ans
或者:
class Solution:
def preorder(self, root: 'Node') -> List[int]:
#递归
res=[]
if not root:
return []
res.append(root.val)
n=len(root.children)
for i in range(n):
res.extend(self.preorder(root.children[i]))
return res
备注:
此题中用到了extend函数,extend函数和append函数的区别:
- 1、append可以追加一个list,一个对象;
- 2、extend则是把两个list连接起来,类似matlab的cat函数。
示例:
list1=[1,2,3]
list2=[4,5,6]
list2.append(list1)
print(list2)
[4, 5, 6, [1, 2, 3]]
list1=[1,2,3]
list2=[4,5,6]
list2.extend(list1)
print(list2)
[4, 5, 6, 1, 2, 3]
590. N 叉树的后序遍历
给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
class Solution:
def postorder(self, root: 'Node') -> List[int]:
ans=[]
if not root:
return []
for child in root.children:
ans+=self.postorder(child)
ans+=[root.val]
return ans