⬅ Previous Topic
Left View of a Binary TreeNext Topic ⮕
Top View of a Binary Tree⬅ Previous Topic
Left View of a Binary TreeNext Topic ⮕
Top View of a Binary Treequeue
and enqueue the root node.levelSize
).i == levelSize - 1
), record its value as part of the right view.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def rightView(root):
if not root:
return []
result = []
queue = [root]
while queue:
levelSize = len(queue)
for i in range(levelSize):
node = queue.pop(0)
if i == levelSize - 1:
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# \ \
# 5 4
root = TreeNode(1, TreeNode(2, None, TreeNode(5)), TreeNode(3, None, TreeNode(4)))
print(rightView(root))
⬅ Previous Topic
Left View of a Binary TreeNext Topic ⮕
Top View of a Binary TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.