Python 3.x 从父数组构造二叉树
这是一个gfg问题 我的代码是-Python 3.x 从父数组构造二叉树,python-3.x,data-structures,binary-tree,Python 3.x,Data Structures,Binary Tree,这是一个gfg问题 我的代码是- class newNode: def __init__(self,data): self.data = data self.left = None self.right = None def inorder(root): if root: inorder(root.left) print(root.data) inorder(root.right)
class newNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def inorder(root):
if root:
inorder(root.left)
print(root.data)
inorder(root.right)
def bstfromarr(first,root,c,arr):
if c not in arr:
return
if root is None:
x = arr.index(c)
root = newNode(x)
if c == -1:
first = root
arr[x] = None
bstfromarr(first,root.left,x,arr)
bstfromarr(first,root.right,x,arr)
return first
arr = [-1,0,0,1,1,3,5]
first = (bstfromarr(None,None,-1,arr))
inorder(first)
树的构造没有任何错误。我面临的问题是如何返回此树的根并打印树的顺序遍历。在运行上面的树时,我得到的答案只有0。有人能指引我吗
谢谢大家! 不幸的是,函数
bstfromarr
没有正确递归
两行
bstfromarr(第一个,root.left,x,arr)
bstfromarr(第一个,root.right,x,arr)
“左”和“右”节点永远不会被指定值,因此这两行也可能始终是:
bstfromarr(第一,无,x,arr)
bstfromarr(第一,无,x,arr)
不幸的是,函数bstfromarr
没有正确递归
两行
bstfromarr(第一个,root.left,x,arr)
bstfromarr(第一个,root.right,x,arr)
“左”和“右”节点永远不会被指定值,因此这两行也可能始终是:
bstfromarr(第一,无,x,arr)
bstfromarr(第一,无,x,arr)
那么我如何克服这个问题呢?首先,作为一个起点,我认为bstfromarr
简单地获取一个列表(arr
)并输出一个树(由树的根节点指定,它由代码中的newNode
对象表示)。接下来,我将介绍一些小示例。例如,如果arr
没有元素怎么办?一个?两个?对我来说,这总是帮助我在尝试泛化时了解我的代码在做什么。希望这有帮助/有意义,让我知道我是否可以更好地解释或以其他方式提供帮助!那么我怎样才能克服这个问题呢?首先,作为一个起点,我认为bstfromarr
简单地获取一个列表(arr
)并输出一个树(由树的根节点指定,它由代码中的newNode
对象表示)。接下来,我将介绍一些小示例。例如,如果arr
没有元素怎么办?一个?两个?对我来说,这总是帮助我在尝试泛化时了解我的代码在做什么。希望这有帮助/有意义,让我知道我是否可以更好地解释或以其他方式提供帮助!