题目:
给定一棵二叉树,返回该二叉树各层节点的数值。例如,给定二叉树:[3,9,20,null,null,15,7]
,如下图
返回的结果为:
解题思路:
直接对二叉树进行递归遍历,保存遍历到的数值时,再维护一个保存该数值所在层的数组。即遍历结束返回两个list,一个为二叉树的节点值,另一个为对应节点值所在的层数。
代码(Python):
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root==None:
return []
def Iteration(root,List1,List2,count):
List1.append(root.val)
List2.append(count)
if root.left==None and root.right==None:
return
elif root.left==None and root.right!=None:
Iteration(root.right,List1,List2,count+1)
elif root.left!=None and root.right==None:
Iteration(root.left,List1,List2,count+1)
else:
Iteration(root.left,List1,List2,count+1)
Iteration(root.right,List1,List2,count+1)
List1 = []
List2 = []
Iteration(root,List1,List2,0)
output = [[] for i in range(max(List2)+1)]
for i in range(len(List1)):
output[List2[i]].append(List1[i])
return output