无需递归的有序树遍历的C ++程序
如果按顺序遍历二叉树,则首先访问左子树,然后访问根,然后访问右子树。以in_order遍历的升序输出键。这是用于无递归顺序树遍历的C++程序。
算法
Begin
Function inOrder():
Declare a stack s.
Declare the current node as root.
While current node is not null and stack is not empty do
While current node is not null do
Push the current node on the top of the stack
Make the left child node as current node
Point the current node at the top of the stack.
Pop the top most node from the stack
Print the current node.
Make the right node as current node.
Insert some elements at root, left node and right node in stack.
Call the inOrder() function to traverse the tree.
End.范例程式码
#include<bits/stdc++.h>
using namespace std;
struct n {
int d;
struct n* l;
struct n* r;
n (int d) {
this->d = d;
l = r = NULL;
}
};
void inOrder(struct n *root) {
stack<n *> s;
n *current = root;
while (current != NULL || s.empty() == false) {
while (current != NULL) {
s.push(current);
current = current->l;
}
current = s.top();
s.pop();
cout << current->d << " ";
current = current->r;
}
}
int main() {
struct n *root = new n(7);
root->l = new n(6);
root->r = new n(2);
root->l->l = new n(1);
root->l->r = new n(9);
inOrder(root);
return 0;
}输出结果
1 6 9 7 2
热门推荐
10 小侄过生日祝福语简短
11 小店营业的祝福语简短
12 担任老师的祝福语简短
13 饮料吧台祝福语简短大气
14 公司新春搞笑祝福语简短
15 高情商敬酒祝福语简短
16 婚礼祝福语新郎妹妹简短
17 教师答辩通过祝福语简短
18 生女孩红包简短祝福语