Spoiler: I accidentally saw a good binary tree preorder example. The non-recursive operation is worth a look.
Pre-order traversal of a binary tree
The following figure represents a binary tree. Pre-order traversal operation is performed on it, using two methods, recursive and non-recursive operations. .
The traversal result is: 1245367.
1. Recursive operation:
Thought: If the binary tree is empty, return. otherwise
1) Traverse the root node; 2) Traverse the left subtree in order; 3) Traverse the right subtree in order
Code:
void PreOrder(BiTree root)
{
if(root==NULL)
return ;
printf("%c ", root->data); //输出数据
PreOrder(root->lchild); //递归调用,先序遍历左子树
PreOrder(root->rchild); //递归调用,先序遍历右子树
}
2. Non-recursive operations
Idea: Non-recursive pre-order traversal of a binary tree. Pre-order traversal idea: Put the root into the stack first. As long as the stack is not empty, you can pop it up. Every time you pop up a node, remember to push its left and right nodes into the stack. , remember that the right subtree is stacked first, which ensures that the right subtree is always below the left subtree in the stack.
Code:
void PreOrder_Nonrecursive(BiTree T) //先序遍历的非递归
{
if(!T) return ;
stack<BiTree> s;
s.push(T);
while(!s.empty())
{
BiTree temp = s.top();
cout<<temp->data<<" ";
s.pop();
if(temp->rchild)
s.push(temp->rchild);
if(temp->lchild)
s.push(temp->lchild);
}
}
or:
void PreOrder_Nonrecursive(BiTree T) //先序遍历的非递归
{
if(!T) return ;
stack<BiTree> s;
while(T) // 左子树上的节点全部压入到栈中
{
s.push(T);
cout<<T->data<<" ";
T = T->lchild;
}
while(!s.empty())
{
BiTree temp = s.top()->rchild; // 栈顶元素的右子树
s.pop(); // 弹出栈顶元素
while(temp) // 栈顶元素存在右子树,则对右子树同样遍历到最下方
{
cout<<temp->data<<" ";
s.push(temp);
temp = temp->lchild;
}
}
}