[英]I am trying zig zag traversal of a binary tree. it's not printing 5 of the last branch,why?
There is no indentation problem in the code 代码中没有缩进问题
class Node:
def __init__(self,key):
self.data=key
self.left=None
self.right=None
def zig_zag(root):
if not root:
return
s=[]
l=1
s.append(root)
while s:
q=[]
if l%2==1:
for i in reversed(s):
print(i.data,end=' ')
if i.left:q.append(i.left)
if i.right:q.append(i.right)
else:
for i in s:
print(i.data,end=' ')
if i.left:q.append(i.left)
if i.right:q.append(i.right)
print(q)
s=q
l+=1
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(7)
root.left.right=Node(6)
root.right.left=Node(5)
root.right.left=Node(4)
zig_zag(root)
The output i am getting is [1,2,3,4,6,7] instead of [1,2,3,4,5,6,7].can anybody explain that why its not appending 5 from the last branch of the tree 我得到的输出是[1,2,3,4,6,7]而不是[1,2,3,4,5,6,7]。任何人都可以解释为什么它不从最后一个分支追加5树的
Algorithm itself is fine. 算法本身很好。
But you have made a mistake in your "node adding code" 但是您在“节点添加代码”中犯了一个错误
You are setting root.right.left
twice 您两次设置root.right.left
Change 更改
root.right.left=Node(5)
root.right.left=Node(4)
to 至
root.right.left=Node(5)
root.right.right=Node(4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.