In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.