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

    Given a complete binary tree, count the number of nodes.

    Definition of a complete binary tree from Wikipedia:
    In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

    思路

    计算根节点的左右子树的高度,如果高度相等则说明是满二叉树,节点数直接使用公式计算:2^h - 1;

    否则,对左右孩子递归调用,即countNodes(left) + countNodes(right) + 1.

    时间/空间复杂度

    最好情况下为满二叉树,时间复杂度为O(h);

    最坏情况下为O(n) (

    程序

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int countNodes(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int lh = getLeftHeight(root);
            int rh = getRightHeight(root);
            
            if (lh == rh) {
                return (1 << lh) - 1;
            }
            return countNodes(root.left) + countNodes(root.right) + 1;
        }
        
        private static int getLeftHeight(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int count = 0;
            while (root != null) {
                ++count;
                root = root.left;
            }
            
            return count;
        }
        
        private static int getRightHeight(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int count = 0;
            while (root != null) {
                ++count;
                root = root.right;
            }
            
            return count;
        }
    }
    
  • 相关阅读:
    HashMap原理
    高并发架构系列:MQ消息队列的12点核心原理总结
    大话程序员系列:一张图道尽程序员的出路
    java面试题
    SpringBoot框架的使用
    java开发定时任务执行时间
    OpenLayers 3 扩展插件收集
    Vue-cli webpack模板
    Spring的属性文件properties使用注意
    FullBg-网页图片背景自适应大小
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4599527.html
Copyright © 2011-2022 走看看