Leetcode 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.
Subscribe to see which companies asked this question
思路: 这道题刚开始写了个dfs遍历,线性的复杂度却超时了。 因此这道题复杂度应该是log级别的。
二叉树很容易想到二分, 很多二分策略都是log级别的
首先得到这个树的深度n,那么就能得到这个树的节点数目的区间为 [2^(n-1), 2^n-1]
有了这个区间,然后在这个区间内二分,即判断一个答案是否合理。判断的策略是从树顶往下查找(默认给这棵树编了号, 从1开始)
AC代码:
/** * 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: bool ok(TreeNode * root, int target, int left, int right) { if (root == NULL) return false; if(left==right && left == target) return true; if(left<right) { int mid = (left+right)/2; if(target <= mid) { return ok(root->left, target, left, mid); } else return ok(root->right, target, mid+1, right); } return false; } int countNodes(TreeNode* root) { if (root == NULL) return 0; TreeNode * ptr = root; int n = 0; while(ptr) { n++; ptr = ptr->left; } int left_limit = pow(2, n-1) + 0.2; int right_limit = pow(2, n) - 1 + 0.2; int left = left_limit; int right = right_limit; int ans = 0; while(left<=right) { int mid = (left+right)/2; if( ok(root, mid, left_limit, right_limit) ) { ans = max(ans, mid); left = mid+1; } else right = mid-1; } return ans; } };

浙公网安备 33010602011771号