⬅ Previous Topic
Bottom View of a Binary TreeNext Topic ⮕
Check if a Binary Tree is Balanced⬅ Previous Topic
Bottom View of a Binary TreeNext Topic ⮕
Check if a Binary Tree is BalancedcurrentStack
and nextStack
. Push the root node onto currentStack
.leftToRight
to true
to indicate the traversal direction.currentStack
is not empty, do the following:currentStack
is not empty, pop a node from it and record its value.leftToRight
is true, push the node's left child then right child (if they exist) onto nextStack
; otherwise, push the node's right child then left child onto nextStack
.currentStack
with nextStack
and toggle the leftToRight
flag.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def zigzagTraversal(root):
if not root:
return []
result = []
currentStack = [root]
nextStack = []
leftToRight = True
level = []
while currentStack:
node = currentStack.pop()
level.append(node.val)
if leftToRight:
if node.left:
nextStack.append(node.left)
if node.right:
nextStack.append(node.right)
else:
if node.right:
nextStack.append(node.right)
if node.left:
nextStack.append(node.left)
if not currentStack:
result.append(level)
level = []
currentStack, nextStack = nextStack, []
leftToRight = not leftToRight
return result
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print(zigzagTraversal(root))
⬅ Previous Topic
Bottom View of a Binary TreeNext Topic ⮕
Check if a Binary Tree is BalancedYou 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.