非递归算法对完全二叉树的前序遍历
非递归算法对完全二叉树的前序遍历
代码
1 # include<iostream> 2 # include<stack> 3 using namespace std; 4 const int m = 100; 5 struct b 6 { 7 char data; 8 int num; 9 }se[m]; 10 int main() 11 { 12 stack<char>s; 13 int n; 14 cin>>n; 15 for(int i = 0;i < n;i++) 16 { 17 cin>>se[i].data; 18 } 19 se[0].num = 0; 20 int root = se[0].num; 21 s.push(root); 22 while(!s.empty()) 23 { 24 root = s.top(); 25 s.pop(); 26 cout<<se[root].data<<" "; 27 int lc = 2*root+1; 28 int rc = 2*root+2; 29 if(rc < n)s.push(rc); 30 if(lc < n)s.push(lc); 31 } 32 }