【问题标题】:I am trying zig zag traversal of a binary tree. it's not printing 5 of the last branch,why?我正在尝试对二叉树进行曲折遍历。它没有打印最后一个分支的 5 个,为什么?
【发布时间】:2017-07-26 10:07:27
【问题描述】:

代码中不存在缩进问题

    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)

我得到的输出是 [1,2,3,4,6,7] 而不是 [1,2,3,4,5,6,7]。谁能解释为什么它不附加 5树的最后一个分支

【问题讨论】:

    标签: python-3.x binary-tree tree-traversal zigzag


    【解决方案1】:

    算法本身很好。
    但是你在“节点添加代码”中犯了一个错误
    你设置了两次root.right.left

    改变

    root.right.left=Node(5)
    root.right.left=Node(4)
    

    root.right.left=Node(5)
    root.right.right=Node(4)
    

    【讨论】:

    • @Arseiny 是的,即使我注意到了,这样的菜鸟错误。无论如何,谢谢
    猜你喜欢
    • 2019-01-12
    • 2022-01-13
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2020-03-26
    • 2016-10-07
    • 2014-05-07
    • 2012-02-01
    相关资源
    最近更新 更多