Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to print python binary trees from top to bottom

Shulou Source: shulou.com Published: 2022-06-01 14:15:06 10月27日 Update

How to print python binary tree from top to bottom, I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Topic description

Please implement a function to print the binary tree in zigzag order, that is, the first line prints from left to right, the second layer prints from right to left, the third line prints from left to right, and so on.

Total number of nodes list [list [int]]:

Res = []

If not root:

Return res

Q = [root]

# initial traversal from left to right

Fromleft = True

While q:

Curlen = len (Q)

Cur = []

For node in q [: curlen]:

Cur.append (node.val)

If node.left:

Q.append (node.left)

If node.right:

Q.append (node.right)

If fromleft:

Res.append (cur)

Else:

# from right to left, you only need to flip the value of this layer into the result

Res.append (cur [::-1])

# change direction at the end of each layer

Fromleft = not fromleft

Q = Q [curlen:]

Return res

After reading the above, have you mastered how to print the python binary tree from top to bottom? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Direction order topic complexity complexity nodes problems code content solutions methods more no skilled necessary helpless and so on one line that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia OPPO Reno MariaDB Linux Microsoft