Preorder traversal of binary tree (java)

definition

In the preorder traversal, each node is processed before its subtree traversal. This is the easiest traversal method to understand. However, although each node is processed before its subtree, it still needs to retain some information in the process of moving down. After the left subtree is traversed, you must return to the root node to traverse the right subtree. The data structure that can store the information is obviously a stack. Because of the FIFO structure, it can get the information in reverse order and return to the right subtree.

Traversal steps:
1. Visit the root node
2. Traverse the left subtree in the pre-order traversal mode
3. Get the root node and traverse the right sub-tree in the pre-order traversal mode

   /**
     * 前序遍历
     */
    void PreOrder(BinaryTreeNode root) {
    
    
        if (root != null) {
    
    
            System.out.println(root.getData());
            PreOrder(root.getLeft());
            PreOrder(root.getRight());
        }
    }

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/109083741