简体   繁体   English

来自预序位串的二叉树

[英]Binary tree from preorder bitstring

I need to build a binary tree from a preorder bitstring (which is piped into standard input in a stream) and I was wondering if my understanding of this was correct.我需要从预排序位串(通过管道传输到流中的标准输入)构建二叉树,我想知道我对此的理解是否正确。

If I had a preorder bitstring of 11110001000 (where 1 indicates an internal node and 0 indicates an external node), would that result in a binary tree like this?如果我有一个 11110001000 的预购位串(其中 1 表示内部节点,0 表示外部节点),会产生这样的二叉树吗?

 1 / \ 1 0 / \ 1 1 / \ / \ 1 00 0 / \ 0 0

After building the binary tree from the preorder bitstring (which is given through the input), I also need to find the height, path length, and whether the binary tree is complete or not.从前序位串(通过输入给出)构建二叉树后,我还需要找到高度、路径长度以及二叉树是否完整。 However I'm having trouble progressing to the point where I'm able to do this because I don't know how to get started on implementing the preorder bitstring -> binary tree conversion in Java.但是,我在前进到能够做到这一点时遇到了麻烦,因为我不知道如何开始在 Java 中实现预排序位串 -> 二叉树转换。 Could anyone please give hints on how I'd get started on building a binary tree from the preorder bitstring?任何人都可以提供有关我如何开始从预购位串构建二叉树的提示吗?

You can begin fromhere .你可以从这里开始。 And if you know c++, thisarticle will be also useful.而如果你知道 c++,这篇文章也会很有用。

The main idea is to have a Node class, which has references to the left and to the right nodes.主要思想是有一个节点 class,它具有对左右节点的引用。 Then, all you need to do, is navigate through the nodes.然后,您需要做的就是浏览节点。

You can start from this simple program I made some time ago and adapt it to accept a binary string as input instead of the manual input:您可以从我前段时间制作的这个简单程序开始,并将其修改为接受二进制字符串作为输入,而不是手动输入:

import javax.swing.JOptionPane;

class Node {
    int info;
    Node fs;
    Node fd;
}

class BinaryTree {

    public static void main(String[] args) {

        Node tree = null;
        tree = insertRecursivePreorder(tree);

    }

    static Node insertRecursivePreorder (Node n) {
      String input = JOptionPane.showInputDialog("Insert node, 0 to end: \n");
      int dato = Integer.parseInt(input);

      if (dato == 0) {
          n=null;
      } else {
          n=new Node();
          n.info=dato;
          n.fs=insertRecursivePreorder(n.fs);
          n.fd=insertRecursivePreorder(n.fd);
      }
      return n;
    }

}

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

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