我建议这样的事情:
struct node {
int isRoot;
int val;
struct node * left;
struct node * right;
};
int printTree(node *root, int level){
int a = 0,b = 0;
if(level > 0){
if(root->left != NULL){
a = printTree(root->left, level-1);
}else{ a = 1; }
if(root->right !=NULL){
b = printTree(root->right, level-1);
}else{ b = 1: }
}else{
printf("%i", root->val);
return 0;
}
if(isRoot && !(a && b)){
printTree(root, level+1);
}
return a&&b;
}
int main(void){
//get your tree somehow and put the root into
//node *head with only the root node having isRoot as true;
printTree(head, 0);
}
顺便说一句,我不确定这是否会编译,所以将其视为伪代码。
编辑:更新的代码不会那么迟钝。它按级别进行,第一个级别 0 ( root
),然后是级别 1 ( root->left
, root->right
),依此类推。和标志表示何时修剪树(a
节点)。b
NULL