LeetCode——Count Complete Tree Nodes
来源:互联网 发布:55开 知乎 12.26 编辑:程序博客网 时间:2024/05/22 15:44
这个也是讨论区里别人的代码,为免侵权之类的,先在此声明。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int countNodes(TreeNode* root) { if (!root) return 0; if (!root->left && !root->right) return 1; int d = 1; // the depth of the tree int leaves = 0; int dl, dr; while (true){ if (!root->right){ leaves++; break; } dl = depth(root->left); dr = depth(root->right); d = max(d, dl+1); // like binary search if (dl == dr){ leaves += 1<<dl; root = root->right; } else{ root = root->left; } } return (1<<d)-1 + leaves;}
int depth(TreeNode* root){ int d = -1; while (root){ d+= 1; root = root->left; } return d;}};
代码的基本思路是先计算出(完全二叉树的层数-1),因为完全二叉树只可能最后一层不满,前d层相当于一个满二叉树,无须遍历节点,即可得节点数量为(1<<d)-1,再加上最后一层的节点数量,即为完全二叉树的节点数。所以代码的变量命名其实是不合适的,leaves变量的值不是叶节点的数量;同时代码中还有小技巧:depth函数中d的初值是-1,也就是说,返回的是(深度-1)。最后一层的节点数如何计算呢?若根节点的左右子树深度相同,就说明左子树是满的,其最后一层的节点数量可用数学公式直接计算,再迭代计算右子树的最后一层节点数;若深度不同,则右子树比左子树少一层,完全二叉树最后一层的节点都在左子树上,于是就是沿着左子树向下,直到某个节点的左右子树深度相同,可用公式计算。能这样做都是因为完全二叉树的性质:最后一层的节点必定是从左到右排列。
循环什么时候退出呢?当遇到一个节点没有右节点的时候。因为此时,这个节点要么是最后一层的叶节点,要么是一个只有左节点的节点(这样的话其左节点即为最后一层的节点),无论哪种情况,都表明我们对此二叉树的二叉搜索完成了,并令 leaves += 1.
这份代码我觉得思路还是不错的,揣摩了不少时间才堪堪理解。如果有什么理解错误的地方,欢迎批评指正。
0 0
- LeetCode——Count Complete Tree Nodes
- leetcode——Count Complete Tree Nodes
- LeetCode 222. Count Complete Tree Nodes 题解——Java
- [LeetCode] Count Complete Tree Nodes
- leetcode - Count Complete Tree Nodes
- Leetcode: Count Complete Tree Nodes
- [LeetCode]Count Complete Tree Nodes
- LeetCode Count Complete Tree Nodes
- [leetcode] Count Complete Tree Nodes
- leetCode:Count Complete Tree Nodes
- [LeetCode] Count Complete Tree Nodes
- leetcode Count Complete Tree Nodes
- #leetcode#Count Complete Tree Nodes
- leetcode Count Complete Tree Nodes
- LeetCode Count Complete Tree Nodes
- LeetCode - Count Complete Tree Nodes
- leetcode: Count Complete Tree Nodes
- leetcode--Count Complete Tree Nodes
- ios 添加图片的三种方法
- LR性能测试结果样例分析
- npm常用命令
- 开发中的注意事项
- 3401 - Colored Cubes
- LeetCode——Count Complete Tree Nodes
- MySQL的timeout那点事
- IOS多线程
- python 编码问题技巧
- SQL Server中的临时表和表变量
- 通知栏跳转问题
- Thinkphp怎么引入外部文件
- GRE写作必备句型
- Text Kit 入门学习