首页 > 代码库 > Leetcode 199. Binary Tree Right Side View
Leetcode 199. Binary Tree Right Side View
思路一:类似103 Binary Tree Zigzag 的思路,只不过要注意最后边的node有时候是zigzag层的最后一个,有时候是zigzag层的第一个。
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def rightSideView(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: List[int] 13 """ 14 ans = [] 15 stack1 = [] 16 stack2 = [] 17 18 stack1.append(root) 19 direct = True 20 while stack1: 21 self.helper(direct, ans, stack1, stack2) 22 stack1, stack2 = stack2, [] 23 direct = not direct 24 return ans 25 26 def helper(self, direct, ans, stack1, stack2): 27 line = [] 28 while stack1: 29 cur = stack1.pop() 30 if cur != None: 31 line.append(cur.val) 32 if direct == True: 33 stack2.append(cur.left) 34 stack2.append(cur.right) 35 else: 36 stack2.append(cur.right) 37 stack2.append(cur.left) 38 39 if direct == True and line: 40 ans.append(line[-1]) 41 elif direct == False and line: 42 ans.append(line[0]) 43
Leetcode 199. Binary Tree Right Side View
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。