首页 > 代码库 > 222. Count Complete Tree Nodes
222. Count Complete Tree Nodes
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.
解题思路:如何巧妙的利用完全二叉树的性质来减少复杂度是这题的核心。一棵完全二叉树的左右两部分必有一部分是满二叉树。本题就是基于此产生了logn*logn的时间复杂度算法。
/** * 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,*r=root; int hl=0,hr=0; while(l){hl++;l=l->left;} while(r){hr++;r=r->right;} if(hl==hr)return (1<<hl)-1; return 1+countNodes(root->left)+countNodes(root->right); } };
222. Count Complete Tree Nodes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。