White special - whether with a binary search tree -python language

Newer and more comprehensive "data structures and algorithms," the update site, more python, go, waiting for you teaching artificial intelligence: https://www.cnblogs.com/nickchen121/p/11407287.html

A judgment the same, the binary search tree

Binary search tree is a special binary tree, to a certain extent, is based on ideas generated binary search, in its node node at any and all elements of the left sub-tree node in value than the node itself is smaller, and all the elements node of the right subtree greater than the node itself.

Second, the problem introduced

Different from ordinary binary, at any given string of unique numbers, can determine a binary search tree, for example: when 12,5,11,17,16,19,18 given sequence, the two can be determined binary search tree as follows:

Essentially, the left and right node of a binary search tree size according to the nature of boundaries to determine a binary search tree, the most important thing is the order of the sequence number that appears, a small exchange could lead to changes in a binary search tree, therefore sometimes we need to find some way to confirm the two sequences corresponding to whether the binary search tree with a binary search tree.

Third, the analysis example

We most simple example, six kinds of sequences consisting of 1,2,3, and its corresponding binary search tree, first order, in sequence, after, sequence through the results are as follows:

Fourth, explore ways

We might naturally think of two binary search tree traversal are compared with commonly used traversal methods:
preorder, preorder, postorder, sequence traversal of
the following points we will discuss their results.

4.1 preorder

Preorder traversal is always the first left child node of the current node, and then traverse the element itself, after traversing the right child node. Accordingly, the binary search tree in preorder always results in ascending order of all the elements (as shown in line are marked in red); in other words, the result is a preorder not help us determining whether two sequences correspond with a binary search tree.

4.2 traversal sequence

  1. 由于二叉搜索树的构建方式与元素在每一层的分布密切相关,对于出现元素集合完全相同的两个不同的序列,它们各自所对应的二叉搜索树如果在某一层开始出现的元素不相同,那么它们不是同一棵二叉搜索树。
  2. 这也可以由递归的思想来理解,对于特定的某一层来说,由于前一层已经确定,那么将序列中剩下的元素按先后顺序插入树中的合适位置时,其位置也就自动被唯一确定了,每个元素是否能在某一层出现以及在该元素某一层出现的位置是确定死了的,完全由上一层的元素来决定,不存在其他的位置来放置它。
  3. 再者,如果给我们了一棵二叉搜索树的层序遍历结果,我们会发现是可以还原出一整棵二叉搜索树的,这与普通二叉树有些区别。
    因此可以由层序遍历结果完成我们的判断。

4.3 先序遍历

根据一个先序遍历结果(不妨仍以上面的那棵二叉搜索树为例,其先序遍历结果是12,5,11,17,16,19,18),从根节点12开始,根据与12的大小关系,12后面的5和11肯定在左子树中,而17,16,19,18肯定在12的右子树中;在5和11中,根据顺序,5应作为12左子树的根节点,然后11比5大,所以11是5的右子节点,这样左子树判断完毕;在左子树17,16,19,18中,17是根节点,16是17的左子节点、19和18是17的右子树,其中19是17的右子节点,18是19的左子节点。这样我们就完成了整个二叉搜索树的构建。

整合一下,我们看到,在二叉搜索树的概念下,先序遍历的结果可以逐步“二分”,分成比node小和比node大的两部分,分别构成node的左右子树;然后以相同的思路进行二分,即可完成构建。

4.4 后序遍历

后序遍历与先序遍历本质上一样,只是在逻辑上进行了完全翻转(注意不是简单的序列翻转),思路和先序遍历基本相同,仍然需要递归分组,只是需要从遍历结果的最后一个元素开始反向构建。

五、总结

由前述分析讨论可见,在二叉搜索树的概念之下,中序遍历损失的信息量是最大的,但由于它得到的结果的升序特性,这是我们可以用它来判断一棵二叉树是否是二叉搜索树,这是其他几种遍历无法做到的,这也表示了中序遍历与二叉搜索树结合得很紧密。
而层序、先序、后序遍历都可以用来判断两个给定序列是否为同一棵二叉搜索树(这里以先序遍历结果实现如下)。

六、代码实现

# python语言实现

# Judge the same binary search tree

# 由于二叉搜索树不同于二叉树,仅根据二叉搜索树的先序遍历结果就能判定二叉树的唯一形状;
# 因此我们可以通过比较两个二叉搜索树的先序遍历结果来判断他们是否为同一个二叉搜索树;


class node:
    def __init__(self, elem=None, lchild=None, rchild=None):
        self.elem = elem
        self.lchild = lchild
        self.rchild = rchild


class tree:
    def __init__(self, root=node()):
        self.root = root


def bi_search_tree_establish(List):  # 根据输入的列表建立二叉搜索树
    if List:
        mytree = tree(node(List[0]))
        for i in range(1, len(List)):
            temp_node = mytree.root
            while temp_node:
                if List[i] < temp_node.elem:
                    if temp_node.lchild:
                        temp_node = temp_node.lchild
                    else:
                        temp_node.lchild = node(List[i])
                        break
                else:
                    if temp_node.rchild:
                        temp_node = temp_node.rchild
                    else:
                        temp_node.rchild = node(List[i])
                        break
        return mytree
    else:
        return None


def preorder_probing(now_node, pre_L):  # 先序遍历——递归实现
    # print(now_node.elem)
    pre_L.append(now_node.elem)
    if now_node.lchild:
        preorder_probing(now_node.lchild, pre_L)
    if now_node.rchild:
        preorder_probing(now_node.rchild, pre_L)


def cmp(a, b):  # 比较序列函数,Python3的常用函数库里已经没有cmp函数了
    leng = len(a)
    if leng == len(b):
        for i in range(0, leng):
            if a[i] != b[i]:
                # print("False")
                return -1
        # print("True")
        return 0
    else:
        # print("False")
        return -1


if __name__ == "__main__":

    N = int(input())  # 输入n表示需要检测的组数
    S_List = [int(i) for i in input()]  # 输入一个二叉搜索树序列作为标准,与下面的进行比较
    S_Tree = bi_search_tree_establish(S_List)  # 构建标准二叉搜索树

    if S_Tree:
        S_pre_list = []
        preorder_probing(S_Tree.root, S_pre_list)

        for i in range(0, N):
            List = [int(i) for i in input()]  # 输入待比较的二叉搜索树序列
            MyTree = bi_search_tree_establish(List)  # 构建待比较二叉搜索树
            if MyTree:
                pre_list = []
                preorder_probing(MyTree.root, pre_list)

                if cmp(S_pre_list, pre_list) == 0:
                    print("YES")
                else:
                    print("NO")

Guess you like

Origin www.cnblogs.com/nickchen121/p/11562295.html