Python programming prints the binary tree to multiple lines of code
- 2020-06-23 00:45:33
- OfStack
Topic describes
2 tree is printed from top to bottom, and nodes of the same layer are output from left to right. Each layer outputs 1 row.
Ideas:
1. Save the val value of each node with list
2. Save the nodes of each layer:
Calculate the number of nodes in each layer, so as to ensure that the nodes in each layer are illuminated by pop in the next step
Then pop up each node from left to right in turn, and add the corresponding left node and right node (if any) to list.
The code is as follows:
class TreeNode():
def __init__(self,x):
self.val = x
self.left = None
self.right = None
def function(root):
result = []
if not root:
return result
A = []
A.append(root)
while A:
temp = []
size = len(A)
for Node in A:
temp.append(Node.val)
result.append(temp)
for i in range(size):
node = A.pop(0)
if node.left:
A.append(node.left)
if node.right:
A.append(node.right)
return result
conclusion
That's all I have to say about Python programming to print a 2-tree into multiple lines of code. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!