Leetcode 199. Binary Tree Right Side View

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode@ [199] Binary Tree Right Side View (DFS/BFS)

LeetCode 199. Binary Tree Right Side View

[leetcode] 199. Binary Tree Right Side View

[LeetCode] 199. Binary Tree Right Side View Java

LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)

(二叉树 bfs) leetcode 199. Binary Tree Right Side View