Java implements inorder traversal of binary tree

1. Define the node class

class Node {
    
    
    int val;
    Node left;
    Node right;
    Node(int val) {
    
    
        this.val = val;
    }
}

public class BinaryTree {
    
    /**
     * 中序遍历
     * @param root 节点
     */
    public void inorderTraversal(Node root) {
    
    
        if (root != null) {
    
    
            inorderTraversal(root.left);
            System.out.print(root.val + " ");
            inorderTraversal(root.right);
        }
    }
}

1) parsing

First, a Node class is defined to represent the node of the binary tree. The node contains an integer val value, and references to the left and right child nodes.
Then, the BinaryTree class is defined, which contains a method inorderTraversal for implementing inorder traversal.
The order of post-order traversal is: first traverse the left subtree, then traverse the root node, and finally traverse the right subtree.
If the binary tree is empty, return directly. Otherwise, first output the value of the left subtree, then the root node and recursively traverse the right subtree.

2) How to use

First create the nodes of the binary tree, then build the binary tree, and finally call the inorderTraversal method of the BinaryTree class for inorder traversal.


2. Test code

public class TestTree {
    
    
    public static void main(String[] args) {
    
    
        // 构建二叉树
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        // 中序遍历
        BinaryTree bt = new BinaryTree();
        System.out.print("Inorder Traversal: ");
        bt.inorderTraversal(root); // 4 2 5 1 3
    }
}

PS

Java implements preorder traversal of binary tree: https://www.cnblogs.com/miracle-luna/p/17368605.html
Java implements inorder traversal of binary tree: https://www.cnblogs.com/miracle-luna/p /17368610.html
Java implements post-order traversal of binary tree: https://www.cnblogs.com/miracle-luna/p/17368606.html


Guess you like

Origin blog.csdn.net/aikudexiaohai/article/details/130801253