Determine whether a binary tree is a full binary tree

Full binary tree defined: a height is h, and containing 2 ^ h - 1 nodes in the binary tree is called a full binary tree, is called full binary FBT below.

The relationship between the number of nodes of the full binary tree height, easily determine whether the FBT a tree, the tree requires only a high number of nodes which can and tree.

Code:

struct node {
	int val;
	node *left, *right;
};

int height(node *root) {
	if (!root) return 0;
	int left  = height(root->left);
	int right = height(root->right);
	return max(left, right) + 1; 
}


void count(node *root, int &sum) {
	if (root) {
		sum += 1;
		count(root->left);
		count(root->right);
	}
}

bool isFBT(node *root) {
	if (!root) return 1;
	int sum = 0;
	int h = height(root);
	count(root, sum);
	return sum == pow(2, h) - 1;
}
Published 235 original articles · won praise 51 · views 120 000 +

Guess you like

Origin blog.csdn.net/ASJBFJSB/article/details/102826778