222.leetcode.Count Complete Tree Nodes(medium)[完全二叉树 节点个数]
来源:互联网 发布:张红兵 知乎 编辑:程序博客网 时间:2024/05/04 07:09
Given a complete binary tree, count the number of nodes.
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.
/** * 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: //计算完全二叉树的节点数,下面是暴力破解的方式,遍历一遍整棵树 /*void countNodes(TreeNode* root,int &n) { if(root != NULL) ++n; else return; countNodes(root->left,n); countNodes(root->right,n); return; } int countNodes(TreeNode* root) { if(root == NULL) return 0; int n = 0; countNodes(root,n); return n; }*/ int getHeight1(TreeNode *root) { if(root == NULL) return 0; int n = 1; while(root->left != NULL){ n++; root = root->left;} return n; } int getHeight2(TreeNode *root) { if(root == NULL) return 0; int n = 1; while(root->right != NULL){ n++; root = root->right;} return n; } int countNodes(TreeNode* root) { if(root == NULL) return 0; int lheight = getHeight1(root->left); int rheight = getHeight2(root->right); if(lheight == rheight) return pow(2,1+lheight)-1; else return countNodes(root->left)+countNodes(root->right)+1; }};
0 0
- 222.leetcode.Count Complete Tree Nodes(medium)[完全二叉树 节点个数]
- Tree-----222. Count Complete Tree Nodes(统计完全二叉树的节点个数)
- 222. Count Complete Tree Nodes 完全二叉树节点
- LeetCode 222. Count Complete Tree Nodes(完全二叉树节点数统计)
- leetcode 222 Count Complete Tree Nodes (计算完全二叉树节点数)
- 222. Count Complete Tree Nodes | 完全二叉树的节点数
- LeetCode Count Complete Tree Nodes 二叉树
- leetcode 222. Count Complete Tree Nodes 计算满二叉树的节点数量
- [Leetcode 222, Medium] Count Complete Tree Nodes
- Leetcode 222. Count Complete Tree Nodes (Medium) (cpp)
- Count Complete Tree Nodes (求完全二叉树节点树)
- Count Complete Tree Nodes 统计完全二叉树的节点数
- leetcode222---Count Complete Tree Nodes(求完全二叉树节点数)
- LeetCode OJ 之 Count Complete Tree Nodes(计算完全二叉树的结点数目)
- Leetcode 222 Count Complete Tree Nodes 完全二叉树的结点数
- Count Complete Tree Node 计算完全二叉树的节点个数。
- [leetcode] 222.Count Complete Tree Nodes
- [leetcode] 222. Count Complete Tree Nodes
- 构建web应用
- ORA-12560: TNS: 协议适配器错误的解决方法
- 博弈论相关知识文档
- 七牛-获取空间域名(c#)
- Protractor
- 222.leetcode.Count Complete Tree Nodes(medium)[完全二叉树 节点个数]
- Linux简介
- c++之STL(13) STL 算法 - 查找算法(4)find_first_of(b,e,sb,se) find_first_of(b,e,sb,se,bp)
- Javascript 同步异步加载详解 (十足的好文章!!强烈推荐)
- leetcode--34. Search for a Range
- 微信配置模板消息进行订单消息推送[基于测试号]
- Codeforces Round #366 (Div. 2)
- 我的家教——面试
- 递归算法转换为非递归算法