1. 程式人生 > >怎麼判斷一棵樹的所有葉子節點都在同一層

怎麼判斷一棵樹的所有葉子節點都在同一層

給定一棵樹,怎麼判斷它的所有葉子節點都在同一層,這種情況應該是完全二叉樹的一種特例,如下圖:


如果去掉節點6的話,它是一棵完全二叉樹,但是所有的葉子節點不在同一層,下面是層次遍歷的一種方法:

#include<iostream>
#include<vector>
using namespace std;

typedef struct tree_node_s {
	int value;
	struct tree_node_s* lchild;
	struct tree_node_s* rchild;
}tree_node_t;

tree_node_t* createNode(int value) {
	tree_node_t* node = (tree_node_t*)malloc(sizeof(tree_node_t));
	node->value = value;
	node->lchild = NULL;
	node->rchild = NULL;
	return node;
}

bool is_complete_bin_tree(tree_node_t* root) {
	int cur = 0;
	int last = 0;
	int count = 0;
	int node_has_child = 0;
	int node_non_child = 0;
	int expected = 0;
	if (NULL == root)
		return true;
	vector<tree_node_t*> vec;
	tree_node_t* node = NULL;
	vec.push_back(root);
	while (cur < vec.size()) {
		last = vec.size();
		count = 0;
		node_has_child = 0;
		node_non_child = 0;
		while (cur < last) {
			node = vec[cur];
			cout << node->value << " ";
			cur++;
			count++;
			if (node->lchild || node->rchild) {
				node_has_child++;
			} else {
				node_non_child++;
			}
			if (node->lchild) 
				vec.push_back(node->lchild);
			if (node->rchild)
				vec.push_back(node->rchild);
		}
		if (node_non_child > 0 && node_non_child < count)
			return false;
		cout << endl;
		if (count >= expected) {
			expected = node_has_child;
		} else {
			return false;
		}
	}
	return true;
}

int main(int argc, char* argv[]) {
	tree_node_t* root = createNode(1);
	root->lchild = createNode(2);
	root->rchild = createNode(3);
	root->lchild->lchild = createNode(4);
	root->lchild->rchild = createNode(5);
	root->rchild->lchild = createNode(6);
	root->rchild->rchild = createNode(7);
	if (is_complete_bin_tree(root))
		cout << "yes" << endl;
	else
		cout << "non" << endl;
	cin.get();
	return 0;
}