简体   繁体   English

从排序的数组中生成二叉搜索树

[英]Making a binary search tree from a sorted array

Let's say I have a sorted array with [1,2,3,4,5], it should become a binary search tree with this array as its output: [4,2,5,1,3] (the brackets below represent the indices) 假设我有一个带有[1,2,3,4,5]的排序数组,它应成为此数组作为其输出的二进制搜索树:[4,2,5,1,3](下面的括号代表索引)

                               4 (0) 
                              /    \
                           2 (1)    5 (2)
                            /  \
                         1 (3)  3 (4)

While doing some research online, I found a link on this site that I could use to get this: Insert sorted array into binary search tree 在进行一些在线研究时,我在此网站上找到了一个链接,可以用来获取以下信息:将排序后的数组插入二进制搜索树

I wanted to convert this to Python 3 without the use of any classes. 我想将其转换为Python 3,而不使用任何类。 This is what I have so far, but I'm stuck. 到目前为止,这是我所拥有的,但我一直处于困境。

def bstlist(arr,start,end):
    newlst = []
    #start = arr[0]
    #end = arr[-1]
    if start > end:
        return [] #null

    mid = start + (end - start) / 2
    newlst = arr[mid]

I'm particularly confused about how to implement three lines of code in the Java implementation in Python: 我对如何在Python的Java实现中实现三行代码感到特别困惑:

TreeNode node = new TreeNode(arr[mid]);
node.left = sortedArrayToBST(arr, start, mid-1);
node.right = sortedArrayToBST(arr, mid+1, end);

How would I go about implementing them in Python ? 我将如何在Python中实现它们? And is there any other way to solve this in Python than the one listed in the link? 除了链接中列出的方法以外,还有什么其他方法可以用Python解决此问题?

The traditional functional way to represent trees is to use lists or tuples for the nodes. 表示树的传统功能方式是对节点使用列表或元组。 Each node is just a value, a left tree, and a right tree (and a tree is just a node, the root of the tree, or None ). 每个节点只是一个值,一个左树和一个右树(而树只是一个节点,树的根或None )。

Use lists if you want to mutate trees in-place; 如果您想就地变异树木,请使用清单; use tuples if you want to build a persistent tree where you generate new subnodes instead and the old ones are never mutated. 如果要构建一棵持久树,在其中生成新的子节点,而旧子节点永不变异,请使用元组。 Since the Java code you're looking at is mutating nodes, let's go with lists. 由于您正在查看的Java代码是对节点进行突变,因此让我们来看一下列表。

You can of course make this fancier by using a namedtuple in place of tuple or a dataclass (or use attrs off PyPI if you're not using Python 3.7+ and don't want to wait for a backport to your Python version) in place of list . 当然,您可以通过使用namedtuple代替tupledataclass (或者如果您不使用Python 3.7+并且不想等待向后移植到Python版本),在PyPI上使用attrs来使这个想法更出色。的list (Or even just a dict .) This allows you to have nice names like .left (or ['left'] ) in place of sequence operations like [1] , but it doesn't actually change the functionality. (甚至只是一个dict 。)这使您可以使用.left (或['left'] )之类的漂亮名称来代替[1]类的序列操作,但实际上并没有改变功能。 Since we've decided to go with mutable, and we probably don't want to require Python 3.7 in early 2018—and besides, you said you don't want any classes—I'll stick with list . 既然我们决定使用可变的,并且我们可能不想在2018年初要求使用Python 3.7,而且您还说过,您不需要任何类,我会坚持使用list

# TreeNode node = new TreeNode(arr[mid]);
node = [arr[mid], None, None]

# node.left = sortedArrayToBST(arr, start, mid-1);
node[1] = sortedArrayToBST(arr, start, mid-1)

# node.right = sortedArrayToBST(arr, mid+1, end);
node[2] = sortedArrayToBST(arr, mid+1, end)

You really should use classes but if you don't want to you could use dictionaries instead. 您确实应该使用类,但是如果不想,可以使用字典。

def list_to_bst(l):
    if len(l) == 0:
        return None
    mid = len(l) // 2
    return {
        "value": l[mid],
        "left": list_to_bst(l[:mid]),
        "right": list_to_bst(l[mid+1:])
    }

you can then use it like so 然后可以像这样使用它

list_to_bst([1, 2, 3, 4, 5])

You can complete your bstlist function using list: 您可以使用list完成bstlist函数:

def bstlist(arr, st, end):
    newlst = []
    if st > end:
        return []
    mid = st + (end-st)/2
    # adding the root list
    root = [arr[mid]]
    # getting the left list
    left = bstlist(arr, st, mid-1)
    # getting the right list
    right = bstlist(arr, mid+1, end)

    newlst = root + left+ right
    return newlst

calling the bstlist function will return you list, which is the order in which you should insert the number to get a balanced tree . 调用bstlist函数将返回您的列表,这是您插入数字以获得平衡树顺序

Example: 例:

arr = [1,2,3,4,5] arr = [1,2,3,4,5]

bstarr = bstlist(arr, 0, len(arr)-1) bstarr = bstlist(arr,0,len(arr)-1)

you will get bstarr as 你会得到bstarr作为

[3, 1, 2, 4, 5] [3,1,2,4,5]

it means you have to insert 3 first then 1 and so on. 这意味着您必须先插入3,然后再插入1 ,依此类推。

The tree will look like this: 该树将如下所示:

           3
         /   \
        1     4
         \     \
          2     5

To get the output as [3, 1, 4, 2, 5] you have to do level order traversal on the above formed binary search tree. 要获得[ 3,1,4,2,5]的输出您必须对上面形成的二进制搜索树进行级别顺序遍历。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM