102、给定一个二叉树,返回其按层次遍历的节点值(即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其层次遍历结果:
[ [3], [9,20], [15,7] ]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
result=[]
currentnode=[]
if not root:
return result
currentnode.append(root)
while currentnode:
single=[]
l=len(currentnode)
for i in range(l):
current=currentnode.pop(0)
if current.left:
currentnode.append(current.left)
if current.right:
currentnode.append(current.right)
single.append(current.val)
result.append(single)
return result
103、给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
result=[]
currentnode=[]
if not root:
return result
currentnode.append(root)
j=-1
while currentnode:
single=[]
l=len(currentnode)
for i in range(l):
current=currentnode.pop(0)
if current.left:
currentnode.append(current.left)
if current.right:
currentnode.append(current.right)
single.append(current.val)
if j>0:
single=single[::-1]
j=-j
result.append(single)
return result
199、给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
result=[]
currentnode=[root]
while currentnode:
single=[]
l=len(currentnode)
for i in range(l):
current=currentnode.pop(0)
if current.left:
currentnode.append(current.left)
if current.right:
currentnode.append(current.right)
single.append(current.val)
result.append(single)
return [s[-1] for s in result]
执行用时: 56 ms, 在Binary Tree Right Side View的Python3提交中击败了71.15%的用户
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
ret = [root.val]
left = self.rightSideView(root.left)
right = self.rightSideView(root.right)
ret += right + left[len(right):]
return ret
第二个方法很简单