首页 > 其他 > 详细

Leetcode 199. Binary Tree Right Side View

时间:2017-01-26 08:28:38      阅读:308      评论:0      收藏:0      [点我收藏+]

思路一:类似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

原文:http://www.cnblogs.com/lettuan/p/6351251.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!