


Detailed explanation of Java binary tree implementation and specific application cases
Detailed explanation of Java binary tree implementation and specific application cases
Binary tree is a data structure often used in computer science, which can perform very efficient search and sorting operations. In this article, we will discuss how to implement a binary tree in Java and some of its specific application cases.
Definition of Binary Tree
Binary tree is a very important data structure, consisting of the root node (the top node of the tree) and several left subtrees and right subtrees. Each node has at most two child nodes, the child node on the left is called the left subtree, and the child node on the right is called the right subtree. If a node does not have any child nodes, it is called a leaf node or terminal node.
Binary tree implementation in Java
The Node class can be used in Java to represent binary tree nodes. This class contains an int type value and two Node type references left and right, which represent the left side respectively. child node and right child node. The following is a sample code:
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
Implement the basic operations of a binary tree
- Create a binary tree
You can create a binary tree recursively, first create the root node , and then create left subtree and right subtree respectively. The following is a sample code:
public class TreeBuilder { public TreeNode buildTree(int[] array) { if (array == null || array.length == 0) { return null; } return build(array, 0, array.length - 1); } private TreeNode build(int[] array, int start, int end) { if (start > end) { return null; } int mid = (start + end) / 2; TreeNode root = new TreeNode(array[mid]); root.left = build(array, start, mid - 1); root.right = build(array, mid + 1, end); return root; } }
- Find Node
The search operation of the binary tree is very efficient. Generally, it is determined whether to search the left child by comparing the size of the node value and the target value. The tree is still the right subtree. The following is a sample code:
public class TreeSearch { public TreeNode search(TreeNode root, int target) { if (root == null || root.val == target) { return root; } if (root.val > target) { return search(root.left, target); } else { return search(root.right, target); } } }
- Insert node
When inserting a new node into a binary tree, you need to compare the value of the node and the size of the inserted value, and decide based on the comparison result Whether to insert the new node into the left subtree or the right subtree. The following is a sample code:
public class TreeInsert { public TreeNode insert(TreeNode root, int target) { if (root == null) { return new TreeNode(target); } if (root.val > target) { root.left = insert(root.left, target); } else if (root.val < target) { root.right = insert(root.right, target); } return root; } }
- Delete node
Deleting a node is a relatively complex operation and needs to be discussed in several situations. Assume that node A is to be deleted, which can be divided into the following three situations:
- A is a leaf node and can be deleted directly.
- A has only one child node, just replace the child node with its position.
- A has two child nodes. You need to find the smallest node B in its right subtree, replace A with the value of B, and then delete B.
The following is a sample code:
public class TreeDelete { public TreeNode delete(TreeNode root, int target) { if (root == null) { return null; } if (root.val > target) { root.left = delete(root.left, target); } else if (root.val < target) { root.right = delete(root.right, target); } else { if (root.left == null && root.right == null) { return null; } else if (root.left == null) { return root.right; } else if (root.right == null) { return root.left; } else { TreeNode min = findMin(root.right); root.val = min.val; root.right = delete(root.right, min.val); } } return root; } private TreeNode findMin(TreeNode node) { while (node.left != null) { node = node.left; } return node; } }
Specific application cases
Binary trees can solve some common data structure problems, such as finding the kth element, finding the smallest k elements, search the depth of the binary tree, etc.
The following are specific application cases:
- Find the k-th element
The result of in-order traversal of a binary tree is in order, so it can be used Inorder traversal to find the kth element. The following is a sample code:
public class TreeFindKth { private int cnt = 0; public int kthSmallest(TreeNode root, int k) { if (root == null) { return Integer.MAX_VALUE; } int left = kthSmallest(root.left, k); if (left != Integer.MAX_VALUE) { return left; } cnt++; if (cnt == k) { return root.val; } return kthSmallest(root.right, k); } }
- Find the smallest k elements
To find the smallest k elements in a binary tree, you can also use in-order traversal, taking the top k elements. The following is a sample code:
public class TreeFindMinK { public List<Integer> kSmallest(TreeNode root, int k) { List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode current = root; while (current != null || !stack.isEmpty()) { while (current != null) { stack.push(current); current = current.left; } current = stack.pop(); result.add(current.val); if (result.size() == k) { return result; } current = current.right; } return result; } }
- Finding the depth of a binary tree
You can use recursion to find the depth of a binary tree. The following is a sample code:
public class TreeDepth { public int maxDepth(TreeNode root) { if (root == null) { return 0; } return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } }
Summary
This article introduces the implementation of binary trees in Java and some specific application cases. Binary tree is a very efficient data structure that is often used when processing large amounts of data. In practical applications, we can choose different implementation methods according to the characteristics of specific problems to obtain better performance.
The above is the detailed content of Detailed explanation of Java binary tree implementation and specific application cases. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4
