先序遍历(非递归)
void DLRNo(BTreeNode *root, vector<int> &data)
{
if (root == NULL) return;
stack<BTreeNode*> s;
while (root || s.size())
{
while (root)
{
data.push_back(root->val);
s.push(root);
root = root->left;
}
if (s.size())
{
root = s.top();
s.pop();
root = root->right;
}
}
}
后序遍历(非递归)
void LRDNo(BTreeNode* root, vector<int>& arr)
{
if (root == NULL)
return;
stack<BTreeNode*> s;
stack<bool> rChildVisited;
while (root || s.size())
{
while (root)
{
s.push(root);
rChildVisited.push(false);
root = root->left;
}
while (s.size() && rChildVisited.top())
{
rChildVisited.pop();
arr.push_back(s.top()->val);
s.pop();
}
if (s.size())
{
rChildVisited.pop();
rChildVisited.push(true);
root = s.top();
root = root->right;
}
}
}
树的广度优先遍历非递归
void BFS(BTreeNode *root)
{
if (root == NULL)
return;
queue<BTreeNode*> que;
que.push(root);
while (que.size())
{
root=que.front();
que.pop();
cout<<root->val;
if (root->left != NULL)
{
que.push(root->left);
}
if (root->right != NULL)
{
que.push(root->right);
}
}
}