"Leetcode" 199. Binary Tree Right Side View problem Solving report (Python)
Topic Address: https://leetcode.com/problems/binary-tree-right-side-view/description/ topic Description:
Given a binary, imagine yourself standing on the right side to it, return the values of the nodes can From top to bottom.
For example:
Given The following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
should return [1, 3, 4].
The main effect of the topic
Prints out the rightmost element of each layer of the two-fork tree. methods of Solving problems
This question is 102. Binary Tree Level Order traversal duplicate AH. The last question is to directly print the elements of each layer, this is to each layer of elements of the rightmost element, so you can use the previous solution, and then the each layer to take out the
Recursive solution:
# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution (object):
def rightsideview (self, Root): ""
: Type root: TreeNode
: Rtype:list[int] ""
res = []
self.levelorder (root, 0, res) return
[level[-1] for Level in res]
def levelorder (self, root, level, res):
if not Root:return
if Len (res) = = Level:res.append ( [])
res[level].append (root.val)
if Root.left:self.levelOrder (Root.left, Level + 1, res)
if root.right : Self.levelorder (Root.right, Level + 1, RES)
Non-recursive solution, using the queue.
The trick of this problem is that the queue can actually find the last element of the layer using [-1] directly.
Each time you do a while loop, you start a new layer, and for the loop, the trick is to walk directly through the elements that are already in the queue, which is the upper element. In this way, the upper level is traversed, and the new layer joins the queue.
# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution (object):
def rightsideview (self, Root): ""
: Type root: TreeNode
: Rtype:list[int] ""
res = []
if not root:return res
queue = Collections.deque () C18/>queue.append (root) while
queue:
res.append (queue[-1].val) for
i in range (len (queue)):
node = queue.popleft ()
if node.left:
queue.append (node.left)
if node.right:
queue.append ( Node.right) return
Res
Date
March 14, 2018 – the day of Hawking's death