题目:
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
题目的理解:
二叉树按行来观察的话,那就是最后的node排序成数组。
python实现
from typing import List
# 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 is None:
return []
rowNode = [root]
result = [root.val]
while len(rowNode) > 0:
rowNodeTemp = list()
for node in rowNode:
if node is not None:
if node.left is not None:
rowNodeTemp.append(node.left)
if node.right is not None:
rowNodeTemp.append(node.right)
if len(rowNodeTemp) > 0:
result.append(rowNodeTemp[-1].val)
rowNode = rowNodeTemp
return result
想看最优解法移步此处
提交

感谢每日打卡,被困难难度折磨了一个月后,突然发现能力已经提升到中等,么么哒
// END 保持良好的心态,去做自己想做的事
网友评论