当然,下面我将为您详细介绍二叉树前序、中序和后序遍历的迭代写法,并附上C++代码示例
- 前序遍历的迭代写法:
前序遍历的非递归写法使用栈来实现。我们首先将根节点入栈,然后进入循环,直到栈为空。在循环中,弹出栈顶节点,访问该节点的值,并将其右子节点(如果存在)入栈,再将左子节点(如果存在)入栈。最后,由于栈是先进后出的结构,所以左子节点会被后弹出,而先访问。
下面是前序遍历的迭代写法的C++代码示例:
void preorder(TreeNode* root)
{
stack<TreeNode*> my_st;
if (root == nullptr) return;
my_st.push(root);
while(!my_st.empty())
{
TreeNode* top = my_st.top();
my_st.pop();
cout << " tree node: " << top->val << " ";
if(top->rightchild != nullptr) my_st.push(top->rightchild);
if(top->leftchild != nullptr) my_st.push(top->leftchild);
}
}
- 中序遍历的迭代写法:
中序遍历的非递归写法同样使用栈来实现。我们从根节点开始,首先将根节点和其所有的左子节点依次入栈,直到没有左子节点。然后开始循环,每次从栈中弹出一个节点,访问该节点的值,并将其右子节点(如果存在)入栈。
下面是中序遍历的迭代写法的C++代码示例:
void inorder(TreeNode* root)
{
stack<TreeNode*> m_st;
if(root == nullptr) return;
TreeNode* cur = root;
while(!m_st.empty() || cur != nullptr)
{
if (cur != nullptr){
m_st.push(cur);
cur = cur->leftchild;
}
else
{
TreeNode* tmp = m_st.top();
m_st.pop();
cout << "my node : " << tmp->val << " ";
cur = tmp->rightchild;
}
}
}
- 后序遍历的迭代写法:
后序遍历的非递归写法稍微复杂一些,但同样使用栈实现。
下面是后序遍历的迭代写法的C++代码示例:
void postorder(TreeNode* root)
{
stack<TreeNode*> m_st;
vector<int> res;
if (root == nullptr) return;
m_st.push(root);
while(!m_st.empty())
{
TreeNode* top = m_st.top();
m_st.pop();
res.push_back(top->val);
if (top->leftchild != nullptr) m_st.push(top->leftchild);
if (top->rightchild != nullptr) m_st.push(top->rightchild);
}
cout << "my node:";
reverse(res.begin(),res.end());
for(int i = 0; i < res.size(); i++)
{
cout << res[i] << " " ;
}
cout << endl;
}