逻辑,判断当前节点的右子树的最左下角节点是否到达最后一层,
若到达最后一层,则说明当前节点的左子树 是一颗,则用公式计算得到总数,然后 对当前节点的右子树 递归求解、
若当前节点的右子树 的最左下角节点没到最后一层,则当前 节点的 右子树是完全二叉树, 对左子树递归求解。
//当前节点的数,其左子树到最后一次了没?
int getHigh(TreeNode* node, int level){
while(node != nullptr){
level++;
node = node->left;
}
return level -1;
}
int getCBTNum(TreeNode* head, int level, int total){
if(level == total){
return 1;
}
if(getHigh(head->right,level+1) == total){
return pow(2, total - level) + getCBTNum(head->right,level+1,total);
}else{
return pow(2, total - level -1) + getCBTNum(head->left,level+1,total);
}
}
int nodeNum(TreeNode* head){
if(head == nullptr){
return 0;
}
return getCBTNum(head,1,getHigh(head,1));
}
总的代码:
#include
#include
#include
#include
using namespace std;
struct TreeNode{
int value;
TreeNode* left;
TreeNode* right;
};
//当前节点的数,其左子树到最后一次了没?
int getHigh(TreeNode* node, int level){
while(node != nullptr){
level++;
node = node->left;
}
return level -1;
}
int getCBTNum(TreeNode* head, int level, int total){
if(level == total){
return 1;
}
if(getHigh(head->right,level+1) == total){
return pow(2, total - level) + getCBTNum(head->right,level+1,total);
}else{
return pow(2, total - level -1) + getCBTNum(head->left,level+1,total);
}
}
int nodeNum(TreeNode* head){
if(head == nullptr){
return 0;
}
return getCBTNum(head,1,getHigh(head,1));
}
string getTreeWithSerial(TreeNode* head){
if(head == nullptr){
return "#_";
}
char c[8];
sprintf(c,"%d",head->value);
string s = c;
s = s+ '_';
string s1 = getTreeWithSerial(head->left);
string s2 = getTreeWithSerial(head->right);
return s + s1 + s2;
}
TreeNode* getTree(int arr[],int length,int i){
if(i < length){
TreeNode* Treenode = new TreeNode();
Treenode->value = arr[i];
if((2*i+1) < length){
Treenode->left = getTree(arr, length, 2*i+1);
}else{
Treenode->left = nullptr;
}
if((2*i+2)right = getTree(arr, length,2*i+2);
}else{
Treenode->right = nullptr;
}
return Treenode;
}
return nullptr;
}
int main(){
int arr[] = {5,3,8,2,4,6,9,1};
// int arr[] = {1,2};
int length = sizeof(arr)/sizeof(arr[0]);
//建树
TreeNode* head = getTree(arr, length,0);
//前序查看建树是否正确
int num = nodeNum(head);
// cout << "str : "<