作为要准备踏入码农行业的人来说,要准备校招,怎么能不去刷刷LeetCode呢?
589.n叉树的前序遍历
- 题目要求
给定一个 N 叉树,返回其节点值的前序遍历。
- 分析
方法:前序遍历,分别使用递归和非递归实现
class Solution(object):
def preorder(self, root):
if not root:
return []
lists=[]
lists.append(root)
result = []
#self.qianxu(root,result)
while lists:
node =lists.pop()
result.append(node.val)
for c in node.children[::-1]:
lists.append(c)
return result
#递归
def qianxu(self,root,result):
if root is None:
return
result.append(root.val)
for c in root.children:
self.qianxu(c,result)
作为要准备踏入码农行业的人来说,要准备校招,怎么能不去刷刷LeetCode呢?
590.n叉树的后序遍历
- 题目要求
给定一个 N 叉树,返回其节点值的后序遍历。
- 分析
方法:后序遍历,分别使用递归和非递归实现。
class Solution(object):
def postorder(self, root):
if not root:
return []
lists=[]
lists.append(root)
result = []
#self.qianxu(root,result)
while lists:
node =lists.pop()
result.insert(0,node.val)
for c in node.children:
lists.append(c)
return result
#递归
def qianxu(self,root,result):
if root is None:
return
for c in root.children:
self.qianxu(c,result)
result.append(root.val)