我有一棵二叉树:
..............1
............/....\
...........2......3
........../..\......\
.........4....5.....6
..........\........./
...........8.......7
我用(-1)填充缺失值并打印新树(使用下面提到的代码):
..............1
............/.....\
...........2.........3
........../..\....../..\
.........4....5....-1.....6
......../.\.../\..../.\../.\
......-1...8.-1.-1.-1.-1.7.-1
我想将新树插入矩阵而不是打印它。 这是输出树:
1
2 3
4 5 -1 6
-1 8 -1 -1 -1 -1 7 -1
我想制作一个二维数组A
,如下所示:
-1 -1 -1 1 -1 -1 -1 -1
-1 -1 -1 2 3 -1 -1 -1
-1 -1 4 5 -1 6 -1 -1
-1 8 -1 -1 -1 -1 7 -1
我使用以下代码填充缺少的值并打印出树。但是,代码必须直接将其写入数组A
。
from collections import deque
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def traverseLevelOrderAndFillMissingNodes(q, level):
while(len(q) > 1):
current = q.popleft()
if(current == None):
q.append(None)
print(""), ##, end=" ")
level = level - 1
else:
if(current.left == None and level > 0):
current.left = Node(-1)
if(current.right == None and level > 0):
current.right = Node(-1)
if(current.left != None):
q.append(current.left)
if(current.right != None):
q.append(current.right)
print(current.val, end=" ")
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(6)
root.right.right.left = Node(7)
root.left.left.right = Node(8)
q = deque()
q.append(root)
q.append(None)
traverseLevelOrderAndFillMissingNodes(q, 3)
我使用以下代码以(-1)初始化数组:
N = 4
M = 2^N
A = [[(-1) for j in range(M)] for i in range(N)]