zoukankan      html  css  js  c++  java
  • 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 2hnodes inclusive at the last level h.

    c++:

    class Solution {
    public:
        bool isExistNode(TreeNode *root,int h,int m){
            TreeNode *p = root;
            for(int i=h-2;i>=0;i--){
                if(m & (1<<i)) p = p->right;
                else p=p->left;
            }
            return p != nullptr;
        }
        int countNodes(TreeNode* root) {
            if (root == nullptr)
                return 0;
            int h = 0;
            TreeNode* p = root;
            while (p != nullptr) {
                h++;
                p = p->left;
            }
    
            int l = 0;
            int r = (1 << (h - 1)) - 1;
            int m;
            while (l <= r) {
                m = l + ((r-l) >> 1);
                if (isExistNode(root, h, m))
                    l = m + 1;
                else
                    r = m - 1;
            }
            return (1 << (h - 1)) + r;
        }
    };

    java:

    public class Solution {
        public boolean isExistNode(TreeNode root,int h,int m){
            TreeNode p = root;
            for(int i = h-2;i>=0;i--){
                if((m & (1<<i)) != 0) p = p.right;
                else p = p.left;
            }
            return p != null;
            
        }
        public int countNodes(TreeNode root) {
            if(root == null) return 0;
            int h = 0;
            TreeNode p = root;
            while(p != null){
                h++;
                p = p.left;
            }
            
            int l=0;
            int r = (1<<(h-1)) - 1;
            int m;
            while(l<=r){
                m = l+((r-l)>>1);
                if(isExistNode(root,h,m)) l = m+1;
                else r = m-1;
            }
            
            return (1<<(h-1))+r;
            
        }
    }
  • 相关阅读:
    Git安装(操作篇)
    Git安装
    ES6基础练习
    SVN的安装与搭建及使用
    解决SVN文件不显示绿色小钩图标问题
    混入(mixin)
    ref属性与props配置项
    docker-compose部署 Mysql 8.0 主从模式基于GTID
    项目统一处理
    Docker Compose实战
  • 原文地址:https://www.cnblogs.com/wxquare/p/5208522.html
Copyright © 2011-2022 走看看