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;
        }
    
  • 相关阅读:
    NODE 开发 2-3年工作经验 掌握的相关知识
    react 问题
    vue 问题集合 |
    前端实用工具大全, 有任何棘手的实现, 可以来这里拿
    react 入门的好东西 可以做出一个完整的网站
    vue 问题集合
    js 预处理 与 执行 的顺序
    js_6_dom选择
    js_4_函数
    js_3_for_if_try
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9700321.html
Copyright © 2011-2022 走看看