Three traversal methods of binary tree (preorder, middle order, postorder) (PerOrder, InOrder, PostOrder)

1. The traversal of the binary tree (the picture comes from the Internet) There
are three ways to traverse the binary tree: first-order traversal, middle-order traversal, and post-order traversal.

  1. Preorder traversal: root-left-right
  2. Middle-order traversal: left-root-right
  3. Post-order traversal: left-right-root

Insert picture description here
Second, first-order traversal

  1. Create node
struct Node//创建节点
{
    
    
	Node left;
	Node right;
	int value;
};
  1. Recursively implement pre-order traversal
void PerOrder(Node head)//遍历节点
{
    
    
	if (head == NULL)
		return;
	cout << head->value;
	PerOrder(left);
	PerOrder(right);
}
  1. The stack structure realizes the pre-order traversal
    Principle: The stack is used, so the root node data is printed first, then the right child is placed, and then the left child is placed. When the element is taken out, the left child can now be taken out, and then the right child can be taken out.

Three, middle order traversal

  1. Create node
struct Node//创建节点
{
    
    
	Node left;
	Node right;
	int value;
};
  1. Recursively implement in-order traversal
void InOrder(Node head)
{
    
    
	if (head == NULL)
		retun;
		InOrder(head.left);
	cout << head.value<<"  ";//若左孩子为空,则输出叶子节点
		InOrder(head.right);
}
  1. The stack structure realizes the
    principle of in-order traversal : when the node is not empty, the node is put into the stack, and the pointer will point to the left child. When the left child is empty, the top data of the stack is printed, and the top node of the stack is popped out, and the node is the right child Into the stack.
void InOrder(Node head)
{
    
    
	if (head == NULL)
		return;
	stack < Node> q;
	while (!q.empty)
	{
    
    
		if (head != NULL)
		{
    
    
			q.push(head);
			head = head.left;
		}
		else if (head == NULL)
		{
    
    
			head = q.top();
			q.pop();
			cout << head.value << "  ";//若左孩子为空,则输出叶子节点
			head = head.right;
		}
	}
	
}

Fourth, post-order traversal

  1. Create node
struct Node
{
    
    
	Node left;
	Node right;
	int value;
};
  1. Recursively implement post-order traversal
void PostOrder(Node head)
{
    
    
	if (head == NULL)
		return;
	    PostOrder( head.left);
		PostOrder(head.right);
	cout << head.value << "  ";

}
  1. The stack structure realizes the post-order traversal
    Principle: the stack order: root node-right child-left child, then reverse order, and then print the data
void PostOrder(Node head)
{
    
    
	if (head == NULL)
		return;
	stack<Node> q;
	stack<Node>p;
	q.push(head);
	while (!q.empty)
	{
    
    
		head = q.top();
		p.push(head);
		if (head.left != NULL)
			q.push(head.left);
		if (head.right != NULL)
			q.push(head.right);
	}
	while (!p.empty)
	{
    
    
		cout << p.top().value << "  ";
		p.pop();
	}
}

Guess you like

Origin blog.csdn.net/Cxf2018/article/details/104983791