Pre-order middle-order and post-order traversal of binary tree

Definition of traversal

According to a certain strategy, each node in the binary tree is visited in a certain order, so that each node is visited once and only once. This process is called the traversal of the binary tree.
The result of traversal is a linear sequence of binary tree nodes. Non-linear structure linearization.

Strategy: The left child node must be visited before the right child node

Pre-order (root) traverse the binary tree

If the binary tree is empty, return; otherwise,

  • ① Visit the root node;
  • ② Traverse the left subtree of the root node first;
  • ③ Traverse the right subtree of the root node first;

The resulting linear sequences are respectively called pre-order (root) sequences.
Insert picture description here
The pre-order traversal sequence is: ABDGCEF

Intermediate (root) traversal of the binary tree

If the binary tree is empty, return; otherwise,

  • ① In order to traverse the left subtree of the root node;
  • ② Visit the root node;
  • ③In order to traverse the right subtree of the root node;

The resulting linear sequences are respectively called in-order (root) sequences.
The middle order traversal sequence is: DGBAECF

Post-order (root) traversal of the binary tree

If the binary tree is empty, return; otherwise,

  • ① Traverse the left subtree of the root node in the subsequent order;
  • ② Traverse the right subtree of the root node in the subsequent order;
  • ③Visit the root node;

The resulting linear sequences are respectively called post-order (root) sequences.

The post-order traversal sequence is: GDBEFCA

Hierarchical (secondary) traversal of the binary tree

Starting from the first level of the binary tree (ie the root node), traverse layer by layer from top to bottom. In the same layer, the nodes are visited in the order from left to right. The resulting linear sequences are called sequence sequences, respectively.
The layer sequence traversal sequence is: ABCDEFG

Code

//编写前序遍历的方法
	public void preOrder() {
    
    
		System.out.println(this); //先输出父结点
		//递归向左子树前序遍历
		if(this.left != null) {
    
    
			this.left.preOrder();
		}
		//递归向右子树前序遍历
		if(this.right != null) {
    
    
			this.right.preOrder();
		}
	}
	//中序遍历
	public void infixOrder() {
    
    
		
		//递归向左子树中序遍历
		if(this.left != null) {
    
    
			this.left.infixOrder();
		}
		//输出父结点
		System.out.println(this);
		//递归向右子树中序遍历
		if(this.right != null) {
    
    
			this.right.infixOrder();
		}
	}
	//后序遍历
	public void postOrder() {
    
    
		if(this.left != null) {
    
    
			this.left.postOrder();
		}
		if(this.right != null) {
    
    
			this.right.postOrder();
		}
		System.out.println(this);
	}
	

Guess you like

Origin blog.csdn.net/qq_41784749/article/details/113444377