前序遍历的递归和非递归实现
转自:July精选微软等公司数据结构+算法,经典面试100题 43 题
1.前序、中序、后序的递归实现就是将printf访问语句放在递归语句的前、中、后三个位置。
2.非递归实现要借用栈stack来实现。
因为对于一棵树(子树)t,如果t 非空,访问完t 的根结点值后,就应该进入t 的左子树,但此时必须将t 保存起来,以便访问完其左子树后,进入其右子树的访问。
即在t 处设置一个回溯点,并将该回溯点进栈保存。
在整个二叉树前序遍历的过程中,程序始终要做的工作分成俩个部分:
1.当前正在处理的树(子树)
2.保存在栈中等待处理的部分。
//注:当栈中元素位于栈顶即将出栈时,意味着其根结点和左子树已访问完成,
//出栈后,进入其右子树进行访问
1 #include<cstdio> 2 #include<cstdlib> 3 4 struct tnode{ 5 int data; 6 tnode *left; 7 tnode *right; 8 9 tnode(int d = 0):data(d), left(NULL), right(NULL) {} 10 }; 11 12 void insertnode(tnode * & root, int d) 13 { 14 if(root == NULL) 15 { 16 root = new tnode(d); 17 return; 18 } 19 if(d <= root->data) 20 insertnode(root->left, d); 21 else 22 insertnode(root->right, d); 23 } 24 25 // construct a binary ordered tree. 26 tnode * createtree(int *d, int n) 27 { 28 tnode *root = NULL; 29 for(int i = 0; i < n; i++) 30 insertnode(root, d[i]); 31 return root; 32 } 33 34 ////////////////////////////////a simple stack 35 struct stack{ 36 tnode * data[100]; //the datatype is tnode * 37 int top; 38 39 stack(): top(0) {} 40 }; 41 42 void push(stack & s, tnode * n) 43 { 44 if(s.top >= 99) 45 { 46 printf("stack overflow!\n"); 47 return; 48 } 49 s.data[s.top++] = n; 50 } 51 52 tnode * pop(stack &s) 53 { 54 if(s.top <= 0) 55 { 56 printf("stack empty!\n"); 57 return NULL; 58 } 59 return s.data[--s.top]; 60 } 61 62 bool isempty(stack &s) 63 { 64 if(s.top == 0) 65 return true; 66 else 67 return false; 68 } 69 /////////////////////////////////// 70 71 void preorder(tnode *root) 72 { 73 if(root) 74 { 75 printf("%d ", root->data); 76 preorder(root->left); 77 preorder(root->right); 78 } 79 } 80 81 // non recursive 82 void preorder_2(tnode *root) 83 { 84 stack s; 85 while(root || (s.top != 0)) 86 { 87 while(root) 88 { 89 printf("%d ", root->data); 90 push(s, root); //store the root, will be used to find right node 91 root = root->left; 92 } 93 if(s.top != 0) 94 { 95 root = pop(s); 96 root = root->right; 97 } 98 } 99 100 } 101 102 int main(int argc, char **argv) 103 { 104 int d[] = {4, 5, 2, 6, 3, 7, 8}; 105 tnode *root = createtree(d, 7); 106 preorder(root); 107 printf("\n"); 108 preorder_2(root); 109 printf("\n"); 110 return 0; 111 }
                    
                
                
            
        
浙公网安备 33010602011771号