题目描述
链接:https://leetcode-cn.com/problems/binary-tree-right-side-view/
思路及代码
原来想的是用BFS遍历,用一个list保存层次遍历的节点,将所有遍历到的节点(包含空节点)存入list中,最后通过计算的方法,从2i~2(i-1)里面选取最右侧的节点输出。但是这个方法时间较慢,而且比较笨,遂根据答案提示,写了下新的两种方法。
方法一:BFS
bfs遍历队列,用duque保存节点和深度,最后用dict保存各个深度下的最后一个遍历的节点,由于是层次遍历,因此每层最后一个遍历的节点就是我们所需要的改成在右视图下的节点,直接覆盖对应的dict[depth]即可,最后输出dict
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root== None:
return []
dq=deque()
dq.append([root,0])
ans=dict()
depth=-1
while dq:
node,depth = dq.popleft()
ans[depth]=node.val
if node.left:
dq.append([node.left,depth+1])
if node.right:
dq.append([node.right,depth+1])
return [ans[i] for i in range(0,depth+1)]
方法二:右序DFS
对二叉树进行右序DFS,即遍历顺序为:根节点、右节点、左节点。这里采用栈来保存遍历的节点,在栈不为空时,从栈顶取节点,并一次将左右节点加入栈顶,pop时先pop右节点。最后用dict保存右视图下的节点的val值,由于对于一个节点来说会先遍历该节点的右节点,再遍历左节点,因此用setdefault判断当前深度是否已有节点,若已有节点,则不再覆盖。
# 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: TreeNode) -> List[int]:
if root== None:
return []
stack=[[root,0]]
ans=dict()
maxdepth=-1
while stack:
node,depth=stack.pop()
ans.setdefault(depth,node.val)
maxdepth=max(maxdepth,depth)
if node.left:
stack.append([node.left,depth+1])
if node.right:
stack.append([node.right,depth+1])
return [ans[i] for i in range(maxdepth+1)]