平衡二叉树的预序遍历

Pre-ordered traversal of a balanced binary tree

我正在对由排序数组构成的平衡树进行预先排序的遍历,但没有得到预期的结果。

我对此事做了很多研究,这是不得已的做法。我尝试了不同的遍历变体(post 和按顺序),但没有产生预期的输出。下面的代码。

import sys


class Node:
    def __init__(self, d):
        self.data = d
        self.left = None
        self.right = None


# function to convert sorted array to a
# balanced BST
# input : sorted array of integers
# output: root node of balanced BST
def sort_array_to_bst(arr):
    if not arr:
        return None

    # find middle
    mid = (len(arr)) / 2
    mid = int(mid)

    # make the middle element the root
    root = Node(arr[mid])

    # left subtree of root has all
    # values <arr[mid]
    root.left = sort_array_to_bst(arr[:mid])

    # right subtree of root has all
    # values >arr[mid]
    root.right = sort_array_to_bst(arr[mid + 1:])
    return root


# A utility function to print the pre-order
# traversal of the BST
def pre_order(node):
    if not node:
        return
    if root:

        sys.stdout.write(str(node.data) + ' ')
        pre_order(node.left)
        #sys.stdout.write(str(node.data) + ' ')
        pre_order(node.right)
        #sys.stdout.write(str(node.data) + ' ')

if __name__ == '__main__':
    arr = []
    for line in sys.stdin.readline().strip().split(" "):
        arr.append(line)
    # arr = [7, 898, 157, 397, 57, 178, 26, 679]
    # Expected Output = 178 57 26 157 679 397 898
    narr = arr[1:]
    narr.sort()
    root = sort_array_to_bst(narr)
    pre_order(root)

通过标准输入输入的数组是 7 898 157 397 57 178 26 679,预期输出是 178 57 26 157 679 397 898。 实际输出为397 178 157 26 679 57 898

想通了。数组未正确排序。我将 narr.sort() 更改为 narr = sorted(narr, key=int)。对数组进行了适当的排序。