Table of Contents
1. General tree node structure definition
2. Find parent node: Broaden-first traversal (BFS) principle
3. Java implementation
4. Complexity analysis
5. Precautions and summary
Home Java javaTutorial Finding parent nodes in a general tree: Implementation Guide based on breadth-first traversal

Finding parent nodes in a general tree: Implementation Guide based on breadth-first traversal

Aug 29, 2025 am 05:45 AM

Finding parent nodes in a general tree: Implementation Guide based on breadth-first traversal

This tutorial details how to find the parent node of a specified node in a general tree data structure. We will use the Broadness-first traversal (BFS) algorithm to systematically explore the nodes of the tree layer by layer, and efficiently locate the parent of the target node. The article will cover node structure definition, BFS algorithm principles, Java code implementation, time and space complexity analysis, and related precautions to help readers master this core tree operation skills.

1. General tree node structure definition

First, we define the node structure of the general tree. A common tree node usually contains a key for identification, and a child node list, because each node of a common tree can have any number of child nodes.

 import java.util.ArrayList;

public class Node {
    int key; // Node key value ArrayList<node> children = new ArrayList(); // Store the list of child nodes/**
     * Determine whether the current node has child nodes.
     * Although not used directly in the logic of finding parent nodes, it helps to understand node characteristics.
     * @return Return true if there are children, otherwise return false.
     */
    public boolean hasChildren(){
        return !children.isEmpty(); // A more concise way of judgment}
}</node>

2. Find parent node: Broaden-first traversal (BFS) principle

To find the parent node of a node with a specified key value (token), we can use the Breadth-First Search (BFS) algorithm. BFS is an algorithm that explores tree or graph layer by layer, which is ideal for solving problems that need to find the nearest relationship or the shortest path, such as finding the parent node.

Core idea of ​​the algorithm: BFS uses queues (Queues) to manage nodes to be accessed. It starts with the root node, first accesses all the child nodes of the current node, then adds these child nodes to the queue, and then takes the next node from the queue for the same operation until the queue is empty or the target is found.

In a scenario where we look up a parent node, when we take a node p (as a potential parent) from the queue, we will iterate through all its child nodes c. If we find that the key value of a child node c matches the token we are looking for, then the current p is the parent node of our target node, and we can return p immediately. If c does not match, we queue c so that it can be checked as a potential parent in subsequent iterations.

3. Java implementation

The following is the Java implementation code based on the above principle:

 import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class TreeOperations {

    /**
     * Find the parent node of the specified key-value node in the general tree.
     * Implemented using Broadness-first traversal (BFS).
     *
     * @param root tree root node.
     * @param token The key value of the child node to be found.
     * @return If found, return the parent node of the target node; if not found or the target node is the root node (no parent node), return null.
     */
    public static Node findParent(Node root, int token) {
        // If the tree is empty or the root node is empty, return null directly
        if (root == null) {
            return null;
        }

        // Use LinkedList as the implementation of Queue Queue<node> queue = new LinkedList();
        queue.add(root); // Add the root node to the queue as the starting point of the traversal // Breadth priority traversal while (!queue.isEmpty()) {
            Node currentNode = queue.poll(); // Take the current node from the queue, it will serve as a potential parent node // traverse all children of the current node for (Node child : currentNode.children) {
                // If the key value of the child node matches the target token if (child.key == token) {
                    return currentNode; // Found, the current node is the parent node of the target node}
                // If the child node does not match, add it to the queue so that it can be checked as a potential parent node later queue.add(child);
            }
        }

        // After traversing all nodes, it still has not been found, indicating that the target node does not exist or it is the root node (no parent node)
        return null;
    }

    public static void main(String[] args) {
        // Build a sample generic tree // 1
        // /|\
        // 2 3 4
        // / \ \
        // 5 6 7
        Node root = new Node();
        root.key = 1;

        Node node2 = new Node(); node2.key = 2;
        Node node3 = new Node(); node3.key = 3;
        Node node4 = new Node(); node4.key = 4;
        root.children.add(node2);
        root.children.add(node3);
        root.children.add(node4);

        Node node5 = new Node(); node5.key = 5;
        Node node6 = new Node(); node6.key = 6;
        node2.children.add(node5);
        node2.children.add(node6);

        Node node7 = new Node(); node7.key = 7;
        node4.children.add(node7);

        // Test to find Node parentOf6 = findParent(root, 6);
        if (parentOf6 != null) {
            System.out.println("The parent node of node 6 is: " parentOf6.key); // Expected output 2
        } else {
            System.out.println("Not found parent node 6.");
        }

        Node parentOf7 = findParent(root, 7);
        if (parentOf7 != null) {
            System.out.println("The parent node of node 7 is: " parentOf7.key); // Expected output 4
        } else {
            System.out.println("Not found parent node of node 7.");
        }

        Node parentOf1 = findParent(root, 1); // The root node has no parent node if (parentOf1 != null) {
            System.out.println("The parent node of node 1 is: " parentOf1.key);
        } else {
            System.out.println("Not found parent node (or it is the root node)."); // The expected output is not found...
        }

        Node parentOf99 = findParent(root, 99); // Node that does not exist if (parentOf99 != null) {
            System.out.println("The parent node of node 99 is: " parentOf99.key);
        } else {
            System.out.println("Not found parent node of node 99."); // The expected output is not found...
        }
    }
}</node>

4. Complexity analysis

  • Time complexity: O(N), where N is the total number of nodes in the tree. In the worst case, we need to access all nodes in the tree to find the parent node of the target node (e.g., the target node is the last leaf node to be accessed, or the target node does not exist). Each node is accessed at most once (enter once, dequeue once).
  • Space complexity: O(W), where W is the maximum width of the tree (i.e. the maximum number of nodes in any layer). In the worst case, for example, a complete binary tree, the number of nodes in the last layer is close to N/2, and at this time, close to N/2 nodes may be stored in the queue. For a perfectly balanced tree with a height of H, the spatial complexity is O(N). In extreme cases (for example, a flat tree with only one layer and containing all child nodes), the spatial complexity is also O(N).

5. Precautions and summary

  • Parent node of root node: The root node has no parent node. If token happens to be the key value of the root node, the findParent function will return null, which is logical.
  • The target node does not exist: if there is no node matching the token in the tree, the function will also return null.
  • Advantages of BFS: For problems such as finding parent nodes that require traversing all possible paths, BFS can ensure that we discover nodes in hierarchical order and return immediately when the first match is found, which is more efficient.
  • Choice of recursion and iteration: Although some tree traversal problems often adopt recursion (such as depth-first traversal DFS), for problems such as finding parent nodes, breadth-first traversal (BFS) is usually more intuitive and efficient by iterating and coordinating queues. When the currentNode is processed as a potential parent node, if its child matches the token, then the currentNode is immediately its parent node. This hierarchical relationship is naturally reflected in BFS. It is more complicated to directly use recursion (DFS) to find the parent node, and may require additional parameters to pass the parent node information or return a result containing a parent-child pair.

Through this tutorial, you should have mastered the method of finding the parent node of a specified node using breadth-first traversal in a general tree. understand

The above is the detailed content of Finding parent nodes in a general tree: Implementation Guide based on breadth-first traversal. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

Hot Topics

PHP Tutorial
1596
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Building RESTful APIs in Java with Jakarta EE Building RESTful APIs in Java with Jakarta EE Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

Java Performance Optimization and Profiling Techniques Java Performance Optimization and Profiling Techniques Jul 31, 2025 am 03:58 AM

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

A Developer's Guide to Maven for Java Project Management A Developer's Guide to Maven for Java Project Management Jul 30, 2025 am 02:41 AM

Maven is a standard tool for Java project management and construction. The answer lies in the fact that it uses pom.xml to standardize project structure, dependency management, construction lifecycle automation and plug-in extensions; 1. Use pom.xml to define groupId, artifactId, version and dependencies; 2. Master core commands such as mvnclean, compile, test, package, install and deploy; 3. Use dependencyManagement and exclusions to manage dependency versions and conflicts; 4. Organize large applications through multi-module project structure and are managed uniformly by the parent POM; 5.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

See all articles