二进制搜索树如何创建?

编程入门 行业动态 更新时间:2024-10-23 20:23:46
本文介绍了二进制搜索树如何创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我要说一个数组

1 5 4 6 8 9 10 22 17 7 9 3

我想从该数组创建一个二进制搜索树。我需要算法来理解这一点。

我已经阅读了与BST相关的其他内容,例如有序遍历 预购 后置订单,树木漫步,插入删除等

本书没有提供如何创建BST。在这里需要帮助

解决方案

如果您不关心树是否平衡,则很简单:

  • 将树的第一个元素作为头部。
  • 在数组上迭代。如果元素大于节点,则向左(重复左边的孩子的步骤),否则向右(重复右边孩子的步骤)。
  • 如果左边/右边child是空值,在其中插入新值。
  • 保证生成二叉搜索树-只是不平衡。 >

    Suppose i am having an array say

    1 5 4 6 8 9 10 22 17 7 9 3

    I want to create a binary search tree from this array. I need algorithm to understand that.

    I have read rest other things related to BST like inorder traversal preorder postorder, tree walk, insertion deletion etc

    Book has not provided how to create BST. Need help here

    解决方案

    if you do not care about the tree being balanced it is simple:

  • put the first element of the tree as the head.
  • iterate over the array. if an element is bigger than the node take a left(repeat the step for the left child) otherwise take a right(repeat the step for the right child).
  • if the left/right child is a null insert your new value there.
  • guaranteed to produce a binary search tree - just not a balanced one.

    更多推荐

    二进制搜索树如何创建?

    本文发布于:2023-11-29 08:25:07,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1645862.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!