Preface
I saw the iterative writing of binary tree preorder traversal in leetcode. I didn't know what iterative writing of binary tree traversal was at the beginning. It turned out to be non-recursive, which seemed a bit embarrassing! But I find that I still don't know how to write, and then make a record summary to facilitate later learning!
prologue
void PreOrder(TreeNode* root)
{
if(root == NULL) return;
stack<TreeNode*> st;
while(root != NULL || !st.empty())
{
if(root)
{
visit(root);
root = root->left;
}else{
root = st.top();
st.pop();
root = root->right;
}
}
}
Middle order
void inOrder(TreeNode* root)
{
if(root == NULL) return;
stack<TreeNode*> st;
while(root != NULL || !st.empty())
{
if(root)
{
visit(root);
root = root->left;
}else{
root = st.top();
st.pop();
root = root->right;
}
}
}
Post sequence
void postOrder(TreeNode* root)
{
if(root == NULL) return;
stack<TreeNode*> st;
while(root != NULL || !st.empty())
{
if(root)
{
visit(root);
root = root->left;
}else{
root = st.top();
st.pop();
root = root->right;
}
}
}
level
在这里插入代码片
to sum up
If you are not familiar with the routine operations of these undergraduate studies, then record and familiarize yourself!