Leetcode 222 - ount Complete Tree Nodes(二分 + 完全二叉树)

27 篇文章 0 订阅
16 篇文章 0 订阅

题意

给一个完全二叉树,求节点数目。

思路

首先,假设完全二叉树的深度为h,那么0到h - 1都是满的,只有h不一定是满的。

算法1

我们只需要知道最后一层的最后一个不是NULL的节点是哪一个就可以了。

我们假设最后一层的所以节点编号为 [0,2n1](n=h1) 。那么我们二分一下最后一层最后一个非NULL节点就好了。然后去判断这个节点是否存在。

在判断这个节点的时候,我们就需要知道从根节点到这个节点的路径。假设将往左走即为0,往右走即为1。那么节点的编号即为路径。比如最后一层第3个(从0开始),二进制表示为011,那么只需要从根节点左→右→右的走即可。

算法2

利用二叉树本身已经二分 + 满二叉树的性质。

假设我们当前节点为p,p的极左节点(从p一直往左走)的深度等于p的极右节点(从p一直往右走)的深度,那么就说明以p为根节点的子树是一个满二叉树,节点数目可以直接计算不用再搜。

代码

//algorithm1
/**
 * 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 findDepth(TreeNode *p) {
        if (p == NULL) return 0;
        return 1 + findDepth(p->left);
    }

    bool has(int x, TreeNode *p, int dep) {
        dep -= 2; //if dep == 1 || dep == 0
        while (dep >= 0) {
            if (x & (1 << dep)) p = p->right;
            else p = p->left;
            dep--;
        }
        return p;
    }
    int countNodes(TreeNode* root) {
        int dep = findDepth(root);
        //num is coding from 0 to 2^n - 1
        int l = 0, r = (1 << dep - 1) - 1, m = 0, ans = 0;
        while (l <= r) {
            m = l + (r - l >> 1);
            if (has(m, root, dep)) l = m + 1, ans = m;
            else r = m - 1;
        }
        return dep > 0 ? (1 << (dep - 1)) + ans : 0;
    }
};


//algorithm 2
/**
 * 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;
        int hl = 1, hr = 1;
        TreeNode *l = root, *r = root;
        while (l->left) {hl++; l = l->left;}
        while (r->right) {hr++; r = r->right;}
        if (hl == hr) return (1 << hl) - 1;
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值