222-完全二叉树的结点个数

完全二叉树和满二叉树的区别:如果二叉树中除去最后一层节点为满二叉树,且最后一层的结点依次从左到右分布,则此二叉树被称为完全二叉树

由于题中已经告诉我们这是一颗完全二叉树,我们又已知了完全二叉树除了最后一层,其他层都是满的,并且最后一层的节点全部靠向了左边。那我们可以想到,可以将该完全二叉树可以分割成若干满二叉树和完全二叉树满二叉树直接根据层高h计算出节点为2^h-1,然后继续计算子树中完全二叉树节点。那如何分割成若干满二叉树和完全二叉树呢?对任意一个子树,遍历其左子树层高left,右子树层高right,相等左子树则是满二叉树,否则右子树是满二叉树
 
具体解析来自公众号小浩算法:https://mp.weixin.qq.com/s?__biz=MzI2NjI5MzU2Nw==&mid=2247484077&idx=1&sn=907c7cb13bc9b7994f0bf43921b6b1f6&chksm=ea911afddde693ebf618f6be32b884a5385eb1853d26f92033cba2fa5ea8a1da7d599dbf2e54&scene=21#wechat_redirect
 
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int countNodes(TreeNode* root) {
13         if(root==NULL)
14         {
15             return 0;
16         }
17         int left=countlevel(root->left);
18         int right=countlevel(root->right);
19         if(left==right)
20         {
21             return countNodes(root->right)+(1<<left);
22         }
23         else
24         {
25             return countNodes(root->left)+(1<<right);
26         }
27 
28 
29     }
30     int countlevel(TreeNode* root)
31     {
32         int level=0;
33         while(root!=NULL)
34         {
35             level++;
36             root=root->left;
37         }
38         return level;
39     }
40 };
View Code

猜你喜欢

转载自www.cnblogs.com/nxnslc-blog/p/12549501.html
今日推荐