zoukankan      html  css  js  c++  java
  • 二叉树遍历+创建

    数组存储二叉树(下标从1开始)。i>时父节点为i/2;当i2<=节点个数时,左子树为i2;当i2+1<=节点个数时,右子数为2i+1

    
    void PreTra(int i){
    	if(i >= len)
    	    return ;
    	printf("%c",a[i]);
    	PreTra(i*2);
    	PreTra(i*2+1);
    	return ;	
    }
    
    void InTra(int i){
    	if(i >= len)
    	    return ;
        InTra(i*2);
    	printf("%c",a[i]);
    	InTra(i*2+1);
    	return ;	
    }
    
    void LaTra(int i){
    	if(i >= len)
    	    return ;
            LaTra(i*2);
    	LaTra(i*2+1);
    	printf("%c",a[i]);
    	return ;	
    }
    
    
    int main(){
    	int i;
    	char ch;
    	len = 1;
    	while(ch = getchar()){
    		a[len++] = ch;
    		if(ch == '
    ')
    		    break;
    	}
    	len --;
    	PreTra(1);
    	printf("
    ");
    	InTra(1);
    	printf("
    ");
    	LaTra(1);
    	return 0; 
    }
    

    先序递归创建二叉树(链表)

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    using namespace std;
    struct node{
    	char data;
    	node * left;
    	node * right;
    };
    
    void CreateTree(node ** p){
    	char ch = getchar();
    	if(ch == ' '){
    	    *p = NULL;
    		return ;
    	}
    	(*p) = (node*) malloc(sizeof(node));
    	(*p)->data = ch;
    	CreateTree(&((*p)->left));
    	CreateTree(&((*p)->right));
    }
    
    void PreTra(node *p){
    	if(!p)
    	    return ;
    	printf("%c",p->data);
    	PreTra(p->left);
    	PreTra(p->right);
    }
    
    int main(){
    	char ch;
    	node * tree;
    	CreateTree(&tree);
    	PreTra(tree);
    //	printf("Tree
    ");
    	return 0;
    }
    
  • 相关阅读:
    java8
    Python isinstance()
    Python3 File next()
    np.array() 与 np.mat() 比较
    np.nonzero()
    np.dot()
    算法之归并排序的应用 —— 小和问题以及逆序对问题
    递归过程以及递归master公式
    算法之异或运算及其应用
    算法之二分法及其应用
  • 原文地址:https://www.cnblogs.com/jxgapyw/p/5292648.html
Copyright © 2011-2022 走看看