假设二叉树采用二叉链表存储结构存储,试设计一个算法,计算一颗给定二叉树的所有双分支节点的个数
#include <iostream>
#include <stack>
typedef struct treenode{
char data;
struct treenode *left;
struct treenode *right;
}treenode,*ptreenode;
ptreenode buytreenode(char x)
{
ptreenode n=(ptreenode) malloc(sizeof (treenode));
n->data=x;
n->left= nullptr,n->right= nullptr;
return n;
}
ptreenode build_tree()
{
ptreenode root= buytreenode('A');
root->left= buytreenode('B');
root->right= buytreenode('C');
root->left->left= buytreenode('D');
root->left->right= buytreenode('E');
root->right->left= buytreenode('F');
root->right->right= buytreenode('G');
return root;
}
int count(ptreenode root)
{
if(root== nullptr) return 0;
if(root->left&&root->right) return count(root->left)+ count(root->right)+1;
else return count(root->left)+ count(root->right);
}
int main() {
ptreenode root=build_tree();
printf("%3d\n", count(root));
return 0;
}