题解 | #输出二叉树的右视图#
输出二叉树的右视图
http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
- 先构建这个树,然后使用分层打印的方式,每次往最终结果放入最后一个元素即可
- 注意索引对齐,有一个方法就是从刚开始大的方式从上到下
- 还有注意结构体声明就是类申明
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 求二叉树的右视图
# @param xianxu int整型一维数组 先序遍历
# @param zhongxu int整型一维数组 中序遍历
# @return int整型一维数组
#
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def cons(self,xianxu,zhongxu):
if not xianxu:
return None
root = TreeNode(xianxu[0])
index = zhongxu.index(xianxu[0])
root.left = self.cons(xianxu[1:index+1], zhongxu[:index])
root.right = self.cons(xianxu[index+1:], zhongxu[index+1:])
return root
def solve(self , xianxu , zhongxu ):
# write code here
root = self.cons(xianxu,zhongxu)# 构建二叉树
res = []#最终的结果
queue = []
queue.append(root)#开始进入逻辑
while(len(queue)>0):#等效替代
n = len(queue)
path =[]
while(n):
n-=1
node = queue.pop(0)#注意弹栈(又可以弹队列,又把其给删除了)
path.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(path[-1])
path = []
return res
算法解析 文章被收录于专栏
这里主要是算法岗的自我思路总结

查看20道真题和解析