Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to return the node value of sequence traversal of python binary tree

Shulou Source: shulou.com Published: 2022-06-01 14:11:54 09月20日 Update

How to return the node value of sequence traversal of python binary tree? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

[title]

Give you a binary tree and ask you to return the node values obtained by traversing in sequence. (that is, access all nodes layer by layer, from left to right.)

Example:

Binary tree: [3, 9, 10, 20, 6, 5, 5, 7]

three

/\

9 20

/\

15 7

Returns the result of its hierarchical traversal:

[

[3],

[9,20]

[15,7]

]

[ideas]

Using the queue, as long as the queue is not empty, traverse the queue element and add the child node to the new queue, and after traversing, copy the new queue to the original queue.

[code]

Python version

# Definition for a binary tree node.

# class TreeNode (object):

# def _ _ init__ (self, x):

# self.val = x

# self.left = None

# self.right = None

Class Solution (object):

Def levelOrder (self, root):

"

: type root: TreeNode

: rtype: List[List[int]]

"

Queue = [root]

Res = []

# as long as it's not empty, you have to continue traversing

While len (queue) > 0:

Tmp = []

Res_tmp = []

# iterate through all elements

While len (queue) > 0:

Node = queue.pop (0)

If not node:

Continue

Res_tmp.append (node.val)

Tmp.append (node.left)

Tmp.append (node.right)

If len (res_tmp) > 0:

Queue = tmp

Res.append (res_tmp)

Return res

[similar topic]

Sawtooth hierarchical traversal of binary tree

The idea of solving the problem: traversing the layers and reversing the results of the even layers.

Hierarchical traversal of II by binary tree

The idea of solving the problem: hierarchical traversal + reverse order of results.

Sequence traversal of N-ary trees

The idea of solving the problem: hierarchical traversal.

Layer average of binary tree

The idea of solving the problem: hierarchical traversal + averaging all elements of each layer.

This is the answer to the question about how to return the node values of the sequence traversal of the python binary tree. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Levels queues nodes ideas elements results questions more reverse questions help answers original easy similar simple code even content mean Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia MariaDB Redmi macOS Huawei