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;
            
        }
    }
  • 相关阅读:
    PHP04
    PHP03
    PHP02
    PHP01
    jquery attr()方法获取input的checked属性问题
    vue案例
    js基础(数组)
    js基础
    POJ1659 可图性判定
    ZOJ3329 概率DP
  • 原文地址:https://www.cnblogs.com/wxquare/p/5208522.html
Copyright © 2011-2022 走看看