[英]Inserting binary tree into matrix in Python
Lets say I have the following binary tree:假设我有以下二叉树:
..............6
............/....\
...........9......4
........../..\......\
.........5....1.....3
..........\........./
...........0.......7
I would like to print it from the very left to the right:我想从最左边到右边打印它:
5 9 0 6 1 4 7 3
I would like to enter it to a matrix in BF way.我想以 BF 方式将其输入到矩阵中。 So I'll be able to transform the matrix.
所以我将能够转换矩阵。 How can I do it?
我该怎么做? Here is the code for initiating the binary tree:
下面是初始化二叉树的代码:
class Node:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
root.right.right.right = Node(9)
The required matrix:所需矩阵:
0 0 0 6 0 0 0 0
0 0 0 9 4 0 0 0
0 0 5 1 0 3 0 0
0 0 0 0 0 0 7 0
Happy to help :)乐于帮助 :)
res = []
def findMinMax(node, minimum, maximum, hd):
if node is None:
return
if hd < minimum[0] :
minimum[0] = hd
elif hd > maximum[0]:
maximum[0] = hd
findMinMax(node.left, minimum, maximum, hd-1)
findMinMax(node.right, minimum, maximum, hd+1)
def printVerticalLine(node, line_no, hd, ls):
if node is None:
return
if hd == line_no:
ls.append(node.data)
printVerticalLine(node.left, line_no, hd-1,ls)
printVerticalLine(node.right, line_no, hd+1,ls)
def verticalOrder(root):
minimum = [0]
maximum = [0]
findMinMax(root, minimum, maximum, 0)
for line_no in range(minimum[0], maximum[0]+1):
r = []
printVerticalLine(root, line_no, 0,r)
res.append(r)
print(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.