• 222.Count Complete Tree Nodes


        /*
         * 222.Count Complete Tree Nodes 
         * 11.20 By Mingyang
         * 最先各自计算最左边那一束到底的长度,再计算右边到底的长度,如果相等,ok,# of nodes = 2^h -1(计算满树很简单的!)
         * 若不相等,再继续迭代,这样做节省了很多时间
         * T(n)=logn+2T(n/2),最后算出来就是n,其实可以这么理解,每个节点都只是访问了一次,所以还是n。注意树的高度是logn
         * 这个题目设定的就是让你先判断是否为完全树,然后其余的都是一样的
         */
        public int countNodes(TreeNode root) {
            if (root == null)
                return 0;
            int leftHeight = 1, rightHeight = 1;
            // 计算左子树
            TreeNode temp = root.left;
            while (temp != null) {
                temp = temp.left;
                leftHeight++;
            }
            // 计算右子树
            temp = root.right;
            while (temp != null) {
                temp = temp.right;
                rightHeight++;
            }
            if (leftHeight == rightHeight)
                return (1 << leftHeight) - 1;
            // 也可以:(2<<(left-1))-1,这里h是left-1
            return countNodes(root.left) + countNodes(root.right) + 1;
        }
  • 相关阅读:
    centos
    ssh 登录 centos 服务器
    Sql NoSql
    Java
    PHP
    React Hooks使用
    前端优化tips
    Error:Node Sass version 5.0.0 is incompatible with ^4.x 解决
    css换行
    git 关联多个远程仓库
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5579655.html
Copyright © 2020-2023  润新知