222. Count Complete Tree Nodes(Leetcode每日一題-2020.11.24)
Problem
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example
Solution
/**
* 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;
TreeNode *l = root->left;
TreeNode *r = root->right;
int l_depth = 1;
int r_depth = 1;
while(l)
{
l = l->left;
++l_depth;
}
while(r)
{
r = r->right;
++r_depth;
}
if(l_depth == r_depth)
return (1 << l_depth) - 1;
return countNodes(root->left) + 1 + countNodes(root->right);
}
};
相關文章
- LeetCode-Count Complete Tree NodesLeetCode
- 【LeetCode 222_完全二叉樹_遍歷】Count Complete Tree NodesLeetCode二叉樹
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- leetcode每日一題LeetCode每日一題
- Leetcode每日一題(1)LeetCode每日一題
- P2633 Count on a tree 題解
- leetcode刷題--Count PrimesLeetCode
- leetcode刷題--Count and SayLeetCode
- LeetCode每日一題:sort colorsLeetCode每日一題
- The best LeetCode NodesLeetCode
- LeetCode 每日一題「判定字元是否唯一」LeetCode每日一題字元
- Leetcode Swap Nodes in PairsLeetCodeAI
- LeetCode每日一題:Nim遊戲(No.292)LeetCode每日一題遊戲
- LeetCode每日一題: 找不同(No.389)LeetCode每日一題
- LeetCode每日一題: 移除元素(No.27)LeetCode每日一題
- [轉載] cassandra Unable to complete request: one or more nodes were unavailableAI
- LeetCode每日一題: 移動零(No.283)LeetCode每日一題
- LeetCode每日一題:自除數(No.728)LeetCode每日一題
- LeetCode每日一題:迴文數(No.9)LeetCode每日一題
- LeetCode每日一題:兩數之和(No.1)LeetCode每日一題
- LeetCode每日一題:爬樓梯(No.70)LeetCode每日一題
- LeetCode每日一題: 排列硬幣(No.441)LeetCode每日一題
- LeetCode每日一題: 各位相加(No.258)LeetCode每日一題
- LeetCode每日一題:longest palindromic substringLeetCode每日一題
- LeetCode 2024/6 每日一題 合集LeetCode每日一題
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- LeetCode 24 Swap Nodes in PairsLeetCodeAI
- Leetcode-Swap Nodes in PairsLeetCodeAI
- Swap Nodes in Pairs leetcode javaAILeetCodeJava
- Leetcode Count and SayLeetCode
- LeetCode:Count and SayLeetCode
- Leetcode每日一題:面試題16.19.水域大小LeetCode每日一題面試題
- LeetCode每日一題:整數反轉(No.7)LeetCode每日一題
- LeetCode每日一題:求眾數(No.169)LeetCode每日一題
- LeetCode每日一題: 轉置矩陣(No.867)LeetCode每日一題矩陣
- LeetCode每日一題:最長公共字首(No.14)LeetCode每日一題
- LeetCode每日一題: 搜尋插入位置(No.35)LeetCode每日一題
- 【js】Leetcode每日一題-葉子相似的樹JSLeetCode每日一題