zoukankan      html  css  js  c++  java
  • 二叉搜索应用(2)

    1.完全二叉树结点的个数

    1.问题:给一个完全二叉树的根节点,返回该二叉树的结点数。

    2.步骤:

      1.计算左子树和右子树的高度,记为h1,h2

      2.如果h1=h2,则左子树必满,n+=2^h1-1.计算右子树

      3.如果h1>h2,则右子树比满,n+=2^h2-1,计算左子树

      4.如果h1=0,则结束。

    3.实现代码

    int count1(TreeNode* root){
        int n=0;
        n++;
        int h1=0;int h2=0;
        TreeNode* current=root->left;
        while(current!=NULL) {
            h1++;
            current=current->left;
        }
        current=root->right;
        while(current!=NULL) {
            h2++;
            current=current->left;
        }
    
        if(h1==0) return n;//无左右子树
    
        if(h1==h2){//左子树满,统计右子树
            n+=pow(2,h1)-1;
            n+=count1(root->right);
        }else{//右子树满,统计左子树
            n+=pow(2,h2)-1;
            n+=count1(root->left);
        }
        return n;
    }

    2.快速求幂运算

    如pow(3,9)

    1.将9写为1001(二进制)

    2.计算3,3^2,3^4,3^8,其中3^2=3*3,3^4=3^2*3^2

    3.9=1*3+1*3^8

  • 相关阅读:
    YXY-压测
    禅道使用
    抓https包
    数据库基本查询语句
    限制网速 制造测试条件
    测试中认识 sqlite
    Adb 命令
    jmeter 查看提取的参数
    jmeter传入字符时文本显示乱码
    nginx 访问springboot项目
  • 原文地址:https://www.cnblogs.com/lshao/p/8976821.html
Copyright © 2011-2022 走看看