Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Sep 7, 2025. It is now read-only.
/pythonPublic archive

zigzag traversal in a binary tree#120

Merged
abranhe merged 1 commit intoAllAlgorithms:masterfromSakshiiAgrawal:master
Nov 7, 2020
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletionsdata-structures/zigzagtraversal_iterative.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
classNode:
"""
A Node has data variable and pointers to its left and right nodes.
"""

def__init__(self,data):
self.left=None
self.right=None
self.data=data

defmake_tree()->Node:
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
root.left.right=Node(5)
returnroot

defzigzag_iterative(root:Node):
"""
ZigZag traverse by iterative method: Print node left to right and right to left, alternatively.
"""
ifroot==None:
return

# two stacks to store alternate levels
s1= []# For levels to be printed from right to left
s2= []# For levels to be printed from left to right

# append first level to first stack 's1'
s1.append(root)

# Keep printing while any of the stacks has some nodes
whilenotlen(s1)==0ornotlen(s2)==0:

# Print nodes of current level from s1 and append nodes of next level to s2
whilenotlen(s1)==0:
temp=s1[-1]
s1.pop()
print(temp.data,end=" ")

# Note that is left is appended before right
iftemp.left:
s2.append(temp.left)
iftemp.right:
s2.append(temp.right)

# Print nodes of current level from s2 and append nodes of next level to s1
whilenotlen(s2)==0:
temp=s2[-1]
s2.pop()
print(temp.data,end=" ")

# Note that is rightt is appended before left
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Just one small change.rightt toright. Writing well-documented code is extremely important. Try fixing any other issues of the same kind. Code LGTM.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

sure, will do it

iftemp.right:
s1.append(temp.right)
iftemp.left:
s1.append(temp.left)

defmain():# Main function for testing.
"""
Create binary tree.
"""
root=make_tree()
print("\nZigzag order traversal(iterative) is: ")
zigzag_iterative(root)
print()


if__name__=="__main__":
importdoctest

doctest.testmod()
main()


[8]ページ先頭

©2009-2025 Movatter.jp