Java implements preorder 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 preorderTraversal(Node root) {
        if (root != null) {
            System.out.print(root.val + " ");
            preorderTraversal(root.left);
            preorderTraversal(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 includes a method preorderTraversal for implementing preorder traversal.

The order of preorder traversal is: first traverse the root node, then traverse the left subtree, and finally traverse the right subtree.

If the binary tree is empty, return directly. Otherwise, first output the value of the root node, and then recursively traverse the left and right subtrees.

2) How to use

First create the nodes of the binary tree, then build the binary tree, and finally call the preorderTraversal method of the BinaryTree class for preorder 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("Preorder Traversal: ");
        bt.preorderTraversal(root); // 1 2 4 5 3
}

PS

Java realizes  preorder traversal of binary tree : https://www.cnblogs.com/miracle-luna/p/17368605.html

Java realizes  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/130789139