从父数组构造二叉树

时间:2020-07-22 08:53:21

标签: python-3.x data-structures binary-tree

这是gfg探针https://practice.geeksforgeeks.org/problems/construct-binary-tree-from-parent-array/1

我的代码是-

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作为答案。谁能指导我 谢谢!

1 个答案:

答案 0 :(得分:0)

一个问题是,不幸的是,函数bstfromarr无法正确递归。

在两行中

    bstfromarr(first, root.left, x, arr)
    bstfromarr(first, root.right, x, arr)

“左”和“右”节点永远不会被赋值,因此这两行可能总是:

    bstfromarr(first, None, x, arr)
    bstfromarr(first, None, x, arr)