zoukankan      html  css  js  c++  java
  • 完全二叉树的节点个数 Count Complete Tree Nodes

    2018-09-25 16:36:25

    问题描述:

    问题求解:

    单纯遍历了一遍,emmm,果然TLE。

    解题思路就是比较左边树高度和右边树高度,如果相等,那么就是一个满二叉树,返回1 << h - 1即可,如果不是,则递归的计算左右子树的个数。

    时间复杂度:O(logn * logn)

        public int countNodes(TreeNode root) {
            if (root == null) return 0;
            int l = leftHeight(root);
            int r = rightHeight(root);
            if (l == r) return (1 << l) - 1;
            else return 1 + countNodes(root.left) + countNodes(root.right);
        }
        
        private int leftHeight(TreeNode root) {
            if (root == null) return 0;
            return 1 + leftHeight(root.left);
        }
        
        private int rightHeight(TreeNode root) {
            if (root == null) return 0;
            return 1 + rightHeight(root.right);
        } 

    2019-04-15 14:42:44

    其实我根本不用管二叉树的种类,直接递归去计数就可以了,在log(n)的时间复杂度内完成,且速度完胜之前的解法。

    Runtime: 0 ms, faster than 100.00% of Java online submissions for Count Complete Tree Nodes.

        public int countNodes(TreeNode root) {
            if (root == null) return 0;
            return countNodes(root.left) + countNodes(root.right) + 1;
        }
    
  • 相关阅读:
    ubuntu下内核源码树的建立
    删除ubuntu旧版本内核
    设置ubuntu12.04桌面版开机进入命令行模式
    MFC学习笔记(一)向模态对话框传递数据
    redis 映射数据结构粗略
    redis入门
    mybatis总结
    mybatis--mapper配置总结
    mybatis-初步使用
    maven-plugins说明
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9700321.html
Copyright © 2011-2022 走看看