zoukankan      html  css  js  c++  java
  • 222. Count Complete Tree Nodes

    二刷。

    利用Complete Tree的特性,前面N-1层是相等的,可以用POW直接算出来。

    主要是最后有可能不完全的一层怎么数。
    一刷的办法是每一层都看看,深度,左右相等说明这个点是完全的,用平方算就行,不完全就左+右递归。

    
    public class Solution 
    {
        public int countNodes(TreeNode root) 
        {
            if(root == null) return 0;
            
            int left = countLeft(root.left)+1;
            int right = countRight(root.right)+1;
            
            if(left == right) return (1<<left)-1;
            else
            {
                return countNodes(root.left) + countNodes(root.right) + 1;
            }
            
        }
        
        public int countLeft(TreeNode root)
        {
            if(root == null) return 0;
            int res = 0;
            
            TreeNode temp = root;
            while(temp!=null)
            {
                temp = temp.left;
                res++;
            }
            
            return res;
            
        }
        public int countRight(TreeNode root)
        {
            if(root == null) return 0;
            int res = 0;
            
            TreeNode temp = root;
            while(temp!=null)
            {
                temp = temp.right;
                res++;
            }
            
            return res;
            
        }
    }
    


    三刷。

    算一个树有多少个NODE,是个complete tree which means 除了最后一层都是满的,而且最后一层从左到右填充。

    直接遍历TLE。

    利用complete的特性,如果一个树是full的 meaning 所有层都是满的,那么总NODE数量是2 ^ 层数 - 1.

    所以从ROOT开始,每个NODE都看最左最右,如果两边深度一样,那么他是full,直接返还2 ^ 深度 - 1。 不是的话,递归。

    题不难,难的是算Complexity.

    Time Complexlty : O(lgN * lgN) 不是 O(n^2) 因为已经说了是complete tree,不会初恋linkedlist的情况。。

    Space Complexity : O(lgN) 递归lgN次就行了。

    public class Solution {
        public int countNodes(TreeNode root) {
            if (root == null) return 0;
            
            int left = 1, right = 1;
            
            TreeNode temp = root.left;
            while (temp != null) {
                left ++;
                temp = temp.left;
            }
            
            temp = root.right;
            while (temp != null) {
                right ++;
                temp = temp.right;
            }
    
            // this (sub)tree is full
            if (left == right) {
                return (1 << left) - 1;
            } else {
                return 1 + countNodes(root.left) + countNodes(root.right);
            }
        }
    }
    

    一刷二刷我还说,* 2给换成 << 1就不TLE了。其实不是,这里指数的算法,何止是把 * 2换成 << 2那么简单。。。

  • 相关阅读:
    Linux网络相关命令firewalld和netfilter、iptables 使用(6/22)
    Linux时间设置与iptables命令
    负载均衡集群ipvsadm命令及基本用法
    LVS原理详解以及部署
    linux比较两个文件的不同(6/21)
    如何使用sql函数平均值、总数、最小值、最大值
    python中数据类型转换
    使用 getopt 处理命令行长参数
    Mysql常用命令行大全
    C#控制台程序使用Log4net日志组件
  • 原文地址:https://www.cnblogs.com/reboot329/p/6105966.html
Copyright © 2011-2022 走看看