[LeetCode] (medium) 222. Count Complete Tree Nodes

11 篇文章 0 订阅
8 篇文章 0 订阅

https://leetcode.com/problems/count-complete-tree-nodes/

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:

Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6

根据完全二叉树的性质,只需要知道层数和最后一层的节点的个数就可以计算出整棵树的结点个数。

算最后一层节点的个数如果使用层次遍历则开销过大(甚至可以直接加出来树结点个数)

因此不知怎么就想到了用数字的每一位比特表示逐层深入的决策过程,然后使用二分搜索找到最后一层最右侧结点的路径,然后就可以计算出来了

/**
 * 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) {
        static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
        if(root == NULL) return 0;
        
        int dep = 0;
        TreeNode *cur = root;
        
        while(cur->left != NULL){
            ++dep;
            cur = cur->left;
        }
        
        if(dep == 0) return 1;
        // cout << "dep: " << dep << endl;
        
        int lo = 0, hi = (1 << dep)-1;
        
        while(lo < hi){
            int mid = (lo+hi+1)/2;
            int mask = (1 << (dep-1));
            cur = root;
            int cnt = 0;
            
            while(cur != NULL){
                ++cnt;
                if(mid & mask){
                    cur = cur->right;
                }else{
                    cur = cur->left;
                }
                mask >>= 1;
            }
            
            if(cnt == dep+1) lo = mid;
            else hi = mid-1;
        }
        
        // cout << "lo: " << lo << endl;
        
        int mask = (1 << (dep-1));
        int lef = 0;
        int result = 0;
        int cur_lev = 1;
        while(mask){
            result += cur_lev;
            cur_lev *= 2;
            lef *= 2;
            if(lo & mask){
                lef += 1;
            }
            mask >>= 1;
        }
        
        // cout << "left: " << left << endl;
        // cout << "result: " << result << endl;
        result += (lef+1);
        return result;
        
        
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值