Home Java javaTutorial Detailed explanation of binary tree structure in Java

Detailed explanation of binary tree structure in Java

Jun 16, 2023 am 08:58 AM
data structure java language Binary tree

Binary tree is a common data structure in computer science and a commonly used data structure in Java programming. This article will introduce the binary tree structure in Java in detail.

1. What is a binary tree?

In computer science, a binary tree is a tree structure in which each node has at most two child nodes. Among them, the left child node is smaller than the parent node, and the right child node is larger than the parent node. In Java programming, binary trees are commonly used to represent sorting, searching and improving the efficiency of data query.

2. Binary tree implementation in Java

In Java, binary tree implementation usually uses node class (Node Class) and binary tree class (Binary Tree Class). The node class represents each node in the binary tree and can have bytes and attributes for storing data. The binary tree class represents the entire binary tree data structure and has functions such as inserting nodes, deleting nodes, and traversing. The following is a simple Java binary tree implementation:

public class Node {
    int key;
    String value;
    Node leftChild, rightChild;

    public Node(int key, String value) {
        this.key = key;
        this.value = value;
    }
}

public class BinaryTree {
    Node root;

    public void insert(int key, String value) {
        Node newNode = new Node(key, value);
        if (root == null) {
            root = newNode;
        } else {
            Node current = root;
            while (true) {
                if (key < current.key) {
                    if (current.leftChild == null) {
                        current.leftChild = newNode;
                        return;
                    }
                    current = current.leftChild;
                } else {
                    if (current.rightChild == null) {
                        current.rightChild = newNode;
                        return;
                    }
                    current = current.rightChild;
                }
            }
        }
    }

    public Node find(int key) {
        Node current = root;
        while (current.key != key) {
            if (key < current.key) {
                current = current.leftChild;
            } else {
                current = current.rightChild;
            }
            if (current == null) {
                return null;
            }
        }
        return current;
    }

    public void inOrderTraversal(Node node) {
        if (node != null) {
            inOrderTraversal(node.leftChild);
            System.out.println(node.key + ": " + node.value);
            inOrderTraversal(node.rightChild);
        }
    }

    public void preOrderTraversal(Node node) {
        if (node != null) {
            System.out.println(node.key + ": " + node.value);
            preOrderTraversal(node.leftChild);
            preOrderTraversal(node.rightChild);
        }
    }

    public void postOrderTraversal(Node node) {
        if (node != null) {
            postOrderTraversal(node.leftChild);
            postOrderTraversal(node.rightChild);
            System.out.println(node.key + ": " + node.value);
        }
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();

        tree.insert(50, "John");
        tree.insert(25, "Alice");
        tree.insert(75, "Bob");
        tree.insert(15, "Chris");
        tree.insert(33, "Diana");
        tree.insert(60, "Emily");
        tree.insert(90, "Fred");

        Node node = tree.find(33);
        System.out.println("Find key: " + node.key + ", value: " + node.value);

        System.out.println("In-order traversal:");
        tree.inOrderTraversal(tree.root);

        System.out.println("Pre-order traversal:");
        tree.preOrderTraversal(tree.root);

        System.out.println("Post-order traversal:");
        tree.postOrderTraversal(tree.root);
    }
}
Copy after login

The above binary tree code includes three main functions: inserting nodes, searching nodes, and three different traversal methods. The insertion node uses a while loop to insert data in the order of the binary tree; the search node uses a while loop to traverse the tree to search for target data; all three traversal methods are implemented recursively.

3. Binary tree traversal methods

In the above Java code, the program implements three different binary tree traversal methods: in-order traversal, pre-order traversal and post-order traversal. This section will introduce these three traversal methods one by one.

  1. In-order traversal

In-order traversal traverses the nodes in the tree in order from small to large. In Java code, the implementation of in-order traversal uses recursion: for each node, first call its own left node, then print the node data, and finally call its own right node. In this way, all nodes in the tree can be traversed in order from small to large.

  1. Pre-order traversal

Pre-order traversal traverses the nodes in the tree in the order of parent node, left node, and right node. In Java code, the implementation of preorder traversal also uses recursion: for each node, first print the node data, then call its own left node, and finally call its own right node. In this way, all nodes in the tree can be traversed in the order of parent node, left node, and right node.

  1. Post-order traversal

Post-order traversal traverses the nodes in the tree in the order of left node, right node, and parent node. In Java code, the implementation of post-order traversal also uses recursion: for each node, first call its own left node, then call its own right node, and finally print the node data. In this way, all nodes in the tree can be traversed in the order of left node, right node, and parent node.

4. Commonly used binary tree algorithms

The binary tree is a flexible and very useful data structure. In Java programming, the binary tree algorithm is often used. The following are commonly used binary tree algorithms:

  1. Search

Search is one of the most basic functions of binary trees and is also a frequently used function. In Java code, the implementation of search is very simple: for each node, by comparing the size of the node value and the target value, search downwards layer by layer until the target value is found or the entire tree is traversed.

  1. Insertion

Insertion is the function of adding new nodes to the binary tree. At the same time, the inserted new nodes will also follow the sorting order of the binary tree. In Java code, the implementation of insertion is also relatively simple: compare the size of the node to be inserted and the current node, and insert a new node when a suitable position is found.

  1. Delete

Deletion is the function of removing nodes from a binary tree. In Java code, the implementation of deletion is more complicated and requires more considerations. If the deleted node has no child nodes, just delete it directly; if there is only one child node, just move the child node to the position of the deleted node; if the deleted node has two child nodes, you need to find the minimum value of the right child node. node and replace it with the location of the deleted node.

5. Summary

This article introduces the binary tree data structure in Java in detail, including the definition of binary tree, the implementation of nodes and binary tree classes, three different traversal methods and commonly used binary tree algorithms. Binary tree is a widely used data structure, and Java provides many functions and class libraries to assist in the implementation of binary trees. When programming in Java, being proficient in the use and implementation of binary trees can improve program efficiency and the accuracy of data queries.

The above is the detailed content of Detailed explanation of binary tree structure in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

In-depth understanding of reference types in Go language In-depth understanding of reference types in Go language Feb 21, 2024 pm 11:36 PM

Reference types are a special data type in the Go language. Their values ​​do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Feb 23, 2024 am 10:49 AM

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

Learn the secrets of Go language data structures in depth Learn the secrets of Go language data structures in depth Mar 29, 2024 pm 12:42 PM

In-depth study of the mysteries of Go language data structure requires specific code examples. As a concise and efficient programming language, Go language also shows its unique charm in processing data structures. Data structure is a basic concept in computer science, which aims to organize and manage data so that it can be accessed and manipulated more efficiently. By in-depth learning the mysteries of Go language data structure, we can better understand how data is stored and operated, thereby improving programming efficiency and code quality. 1. Array Array is one of the simplest data structures

Java Map Revealed: Tips and Strategies for Fast Data Access Java Map Revealed: Tips and Strategies for Fast Data Access Feb 19, 2024 pm 06:21 PM

JavaMap is a key-value pair-based data structure that allows developers to quickly store and retrieve data. The keys of a Map can be any object, and the values ​​can be any type of data. Each key in the Map can only be associated with at most one value. If multiple values ​​are set for the same key, only the last set value will be retained. There are two main implementations of Map: HashMap: uses a hash table to store key-value pairs. The performance of HashMap depends on how the hash table is implemented, and in most cases HashMap performs better than TreeMap. TreeMap: uses red-black trees to store key-value pairs. The performance of TreeMap is similar to HashMap, but in some cases, the performance of TreeMap can be

PHP SPL data structures: Inject speed and flexibility into your projects PHP SPL data structures: Inject speed and flexibility into your projects Feb 19, 2024 pm 11:00 PM

Overview of the PHPSPL Data Structure Library The PHPSPL (Standard PHP Library) data structure library contains a set of classes and interfaces for storing and manipulating various data structures. These data structures include arrays, linked lists, stacks, queues, and sets, each of which provides a specific set of methods and properties for manipulating data. Arrays In PHP, an array is an ordered collection that stores a sequence of elements. The SPL array class provides enhanced functions for native PHP arrays, including sorting, filtering, and mapping. Here is an example of using the SPL array class: useSplArrayObject;$array=newArrayObject(["foo","bar","baz"]);$array

See all articles