打印树

假设node的子节点都在children数组中。

void print_ast(Node* ptr, int depth) 
{
  	int i;
    	int n = (depth - 1) * 2;
    	for (i = 0; i < n; i++) {
 	       putchar(buffer[i]);
	}
	if (depth > 0) {
		putchar('|');
		putchar('_');
	}
    	n = depth * 2;
    	buffer[n] = '|';
    	buffer[n + 1] = ' ';
    	if (!ptr->isLeaf()) {
        	printf("%s
", ptr->name);
    	} else {
        	printf("33[1;33m%s33[0m
", ptr->name);
    	}
    	for (i = 0; i < ptr->size; i++) {
        	if (i == ptr->size - 1) {
            		buffer[n] = ' ';
        	}
        	print_ast(ptr->children[i], depth + 1);
    	}
}

  

原文地址:https://www.cnblogs.com/shenbingyu/p/4961528.html