search
HomeJavajavaTutorialHow to build a binary tree using java

How to build a binary tree using java

Apr 03, 2017 am 10:15 AM
Binary tree

Directory:

1. Put a Assign the value of array to a binary tree

2. Specific code

Note:

1. The subscript of the parent node array ranges from 0 to n/2 -1, but it should be less than n/2-1 when traversing, because the last The parent node may not have a right child. When n/2-1 is an odd number, it has a right child, and when it is an even number, it only has a left child.

##2. Node. The subscript of the left child is 2n+1, and the subscript of the right child is 2n+2

##1. Tree construction method




2. Specific code

package tree;  
  
import java.util.LinkedList;  
import java.util.List;  
  
/** 
 * 功能:把一个数组的值存入二叉树中,然后进行3种方式的遍历 
 *  
 * 参考资料0:数据结构(C语言版)严蔚敏 
 *  
 * 参考资料1:http://zhidao.baidu.com/question/81938912.html 
 *  
 * 参考资料2:http://cslibrary.stanford.edu/110/BinaryTrees.html#java 
 *  
 * @author ocaicai@yeah.net @date: 2011-5-17 
 *  
 */  
public class BinTreeTraverse2 {  
  
    private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
    private static List<Node> nodeList = null;  
  
    /** 
     * 内部类:节点 
     *  
     * @author ocaicai@yeah.net @date: 2011-5-17 
     *  
     */  
    private static class Node {  
        Node leftChild;  
        Node rightChild;  
        int data;  
  
        Node(int newData) {  
            leftChild = null;  
            rightChild = null;  
            data = newData;  
        }  
    }  
  
    public void createBinTree() {  
        nodeList = new LinkedList<Node>();  
        // 将一个数组的值依次转换为Node节点  
        for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {  
            nodeList.add(new Node(array[nodeIndex]));  
        }  
        // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树  
        for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {  
            // 左孩子  
            nodeList.get(parentIndex).leftChild = nodeList  
                    .get(parentIndex * 2 + 1);  
            // 右孩子  
            nodeList.get(parentIndex).rightChild = nodeList  
                    .get(parentIndex * 2 + 2);  
        }  
        // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理  
        int lastParentIndex = array.length / 2 - 1;  
        // 左孩子  
        nodeList.get(lastParentIndex).leftChild = nodeList  
                .get(lastParentIndex * 2 + 1);  
        // 右孩子,如果数组的长度为奇数才建立右孩子  
        if (array.length % 2 == 1) {  
            nodeList.get(lastParentIndex).rightChild = nodeList  
                    .get(lastParentIndex * 2 + 2);  
        }  
    }  
  
    /** 
     * 先序遍历 
     *  
     * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已 
     *  
     * @param node 
     *            遍历的节点 
     */  
    public static void preOrderTraverse(Node node) {  
        if (node == null)  
            return;  
        System.out.print(node.data + " ");  
        preOrderTraverse(node.leftChild);  
        preOrderTraverse(node.rightChild);  
    }  
  
    /** 
     * 中序遍历 
     *  
     * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已 
     *  
     * @param node 
     *            遍历的节点 
     */  
    public static void inOrderTraverse(Node node) {  
        if (node == null)  
            return;  
        inOrderTraverse(node.leftChild);  
        System.out.print(node.data + " ");  
        inOrderTraverse(node.rightChild);  
    }  
  
    /** 
     * 后序遍历 
     *  
     * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已 
     *  
     * @param node 
     *            遍历的节点 
     */  
    public static void postOrderTraverse(Node node) {  
        if (node == null)  
            return;  
        postOrderTraverse(node.leftChild);  
        postOrderTraverse(node.rightChild);  
        System.out.print(node.data + " ");  
    }  
  
    public static void main(String[] args) {  
        BinTreeTraverse2 binTree = new BinTreeTraverse2();  
        binTree.createBinTree();  
        // nodeList中第0个索引处的值即为根节点  
        Node root = nodeList.get(0);  
  
        System.out.println("先序遍历:");  
        preOrderTraverse(root);  
        System.out.println();  
  
        System.out.println("中序遍历:");  
        inOrderTraverse(root);  
        System.out.println();  
  
        System.out.println("后序遍历:");  
        postOrderTraverse(root);  
    }  
  
}

Output result:

先序遍历:  
1 2 4 8 9 5 3 6 7   
中序遍历:  
8 4 9 2 5 1 6 3 7   
后序遍历:  
8 9 4 5 2 6 7 3 1

The above is the detailed content of How to build a binary tree using java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?Apr 19, 2025 pm 08:27 PM

When using MyBatis-Plus or tk.mybatis...

How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?Apr 19, 2025 pm 08:24 PM

How to query personnel data through natural language processing? In modern data processing, how to efficiently query personnel data is a common and important requirement. ...

How to parse next-auth generated JWT token in Java and get information in it?How to parse next-auth generated JWT token in Java and get information in it?Apr 19, 2025 pm 08:21 PM

In processing next-auth generated JWT...

Why can't JavaScript directly obtain hardware information on the user's computer?Why can't JavaScript directly obtain hardware information on the user's computer?Apr 19, 2025 pm 08:15 PM

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

Circular dependencies appear in the RuoYi framework. How to troubleshoot and solve the problem of dynamicDataSource Bean?Circular dependencies appear in the RuoYi framework. How to troubleshoot and solve the problem of dynamicDataSource Bean?Apr 19, 2025 pm 08:12 PM

RuoYi framework circular dependency problem troubleshooting and solving the problem of circular dependency when using RuoYi framework for development, we often encounter circular dependency problems, which often leads to the program...

When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure?When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure?Apr 19, 2025 pm 08:09 PM

About SpringCloudAlibaba microservices modular development using SpringCloud...

Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Apr 19, 2025 pm 08:06 PM

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)