Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the level sequence traversal of binary trees in python

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to traverse the level order of binary trees in python. Many people may not know much about it. In order to make you understand better, the editor summarized the following content for you. I hope you can get something according to this article.

Binary tree-level sequential traversal

Given a binary tree, the level order that returns the values of its nodes. (that is, from left to right, step by step).

For example:

Given binary tree [3,9,20,null,null,15,7]

3 / 9 20 / 15 7

Return its level order traversal as:

[[3], [9,20], [15,7]]

Ideas for solving the problem:

Dual queues are used for processing.

Use the current queue current to process all nodes at this layer and record the information at this layer in vector. Use next to record the node information of the next layer.

After the current queue is processed, the vector of the information in this layer is stored in the result vector. Clear the vector that stores the information at this layer. Swap current with next. Then reprocess the current queue.

The code is as follows:

/ * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode* left; * TreeNode* right; * TreeNode (int x): val (x), left (NULL), right (NULL) {} *}; * / class Solution {public: vector levelOrder (TreeNode* root) {vector result; queue current,next; vector level; if (NULL = = root) return result Current.push (root); while (current.size () > 0) {while (current.size () > 0) {TreeNode * p = current.front (); current.pop (); level.push_back (p-> val) If (p-> left) next.push (p-> left); if (p-> right) next.push (p-> right);} result.push_back (level); level.clear (); current.swap (next);} return result After reading the above, do you have any further understanding of how to analyze the level order traversal of binary trees in python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report