预先遍历平衡二叉树的遍历

问题描述 投票:1回答:1

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

我已就此事做过大量研究,这是最后的手段。我尝试了不同的遍历(post和inorder)变量,但没有产生预期的输出。代码如下。

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)

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

python-3.x binary-tree binary-search-tree tree-traversal
1个回答
0
投票

弄清楚了。数组未正确排序。我改变了narr.sort(),改为narr = sorted(narr, key=int)。这对阵列进行了精细排序。

© www.soinside.com 2019 - 2024. All rights reserved.