首页 > 代码库 > 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