老师布置的作业求大佬解释一下代码
class BinaryTree:
def __init__(self, num):
self.val = num
self.left = None
self.right = None
if type(num) == list:
self.num = num
for n in num:
self.insert(n)
else:
self.num = num
def insert(self, num):
bt = self
while True:
if num <= bt.num:
if bt.left == None:
bt.left = BinaryTree(num)
break
else:
bt = bt.left
else:
if bt.right == None:
bt.right = BinaryTree(num)
break
else:
bt = bt.right
class Solution:
def binaryTreePaths(self, root):
def construct_paths(root, path):
if root:
path += str(root.num)
if not root.left and not root.right:
paths.append(path)
else:
path += '->'
construct_paths(root.left, path)
construct_paths(root.right, path)
paths = []
construct_paths(root, '')
return paths
num = list(map(int,input().split()))
bt = BinaryTree(num)
s = Solution()
l = s.binaryTreePaths(bt)
for i in l:
print(i)
老师布置了一道题死活看不懂求大佬帮忙讲解一下代码。 二叉树我现在在看到都怕了{:10_254:} 本帖最后由 大马强 于 2021-7-30 19:07 编辑
首先它节点的创建用到了递归,是有规律的,左小右大
其次遍历方式应该是一个前驱遍历,也是用到递归,一般前驱的遍历结果为5213467
前驱遍历思路为 根节点 左节点 右节点
从结果可以看出
5 2 1 (根左左)
5 2 3 4 (根左右右) 这里你看将2 看作根节点理解 也就是(根右右)
5 6 7 (根右右)
这道题中,你要知道递归和二叉树的遍历,你才能理解,欢迎追问{:10_281:}
页:
[1]