LeetCode - 222 - Count Complete Tree Nodes
2017-07-28 17:46
288 查看
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.
问一颗完全二叉树有多少个结点。
遍历一遍就可以,但是就完全没用到完全二叉树的性质。
完全二叉树的定义如下:
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
根据完全二叉树的这个性质,可以这样来求解完全二叉树中节点的个数。
对于一个节点node,计算它最左端的节点到node的深度为hle,计算它最右端的节点到node的深度是hri;
如果hle和hri相等,那么以node为根节点的树是一棵满二叉树,此时以node为根节点的树的节点个数是pow(2,hle)-1;
如果hle和hri不相等,递归求解node的左子树的节点数和右子树的节点数。
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.
问一颗完全二叉树有多少个结点。
遍历一遍就可以,但是就完全没用到完全二叉树的性质。
完全二叉树的定义如下:
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
根据完全二叉树的这个性质,可以这样来求解完全二叉树中节点的个数。
对于一个节点node,计算它最左端的节点到node的深度为hle,计算它最右端的节点到node的深度是hri;
如果hle和hri相等,那么以node为根节点的树是一棵满二叉树,此时以node为根节点的树的节点个数是pow(2,hle)-1;
如果hle和hri不相等,递归求解node的左子树的节点数和右子树的节点数。
/** * 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 == NULL) return 0; int hle = 0, hri = 0; TreeNode *le = root, *ri = root; while (le) { hle++; le = le->left; } while (ri) { hri++; ri = ri->right; } if (hle == hri) return (1 << hle) - 1; return countNodes(root->left) + countNodes(root->right) + 1; } };
相关文章推荐
- LeetCode(222) Count Complete Tree Nodes
- LeetCode222:Count Complete Tree Nodes
- [leetcode] 222 Count Complete Tree Nodes
- Leetcode[222]-Count Complete Tree Nodes
- Leetcode 222: Count Complete Tree Nodes
- [Leetcode 222, Medium] Count Complete Tree Nodes
- 【LeetCode 222_完全二叉树_遍历】Count Complete Tree Nodes
- leetcode 222: Count Complete Tree Nodes
- leetcode #222 Count Complete Tree Nodes
- [LeetCode222]Count Complete Tree Nodes
- LeetCode 222 Count Complete Tree Nodes
- LeetCode 222 Count Complete Tree Nodes
- leetcode 222: Count Complete Tree Nodes
- leetcode 222:Count Complete Tree Nodes
- [LeetCode 222]Count Complete Tree Nodes
- [leetcode 222]Count Complete Tree Nodes
- leetCode(19):Count Complete Tree Nodes 分类: leetCode 2015-06-22 08:32 222人阅读 评论(0) 收藏
- LeetCode222 Count Complete Tree Nodes
- 8.8 LeetCode 222 Count Complete Tree Nodes
- Java for LeetCode 222 Count Complete Tree Nodes