• 222. Count Complete Tree Nodes


    https://leetcode.com/problems/count-complete-tree-nodes/#/description

    http://www.cnblogs.com/EdwardLiu/p/5058570.html

    iven 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.

    递归树高法

    复杂度

    时间 O(N) 空间 O(1)

    思路

    完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的,即最后一层也是满的,则以该节点为根的树其节点一共有2^h-1个。如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。

    注意

    • 这里在左节点递归时代入了上次计算的左子树最左深度减1,右节点递归的时候代入了上次计算的右子树最右深度减1,可以避免重复计算这些深度

    • 做2的幂时不要用Math.pow,这样会超时。用1<<height这个方法来得到2的幂

    /**
     * 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 leftHeight = countLeft(root);
            int rightHeight = countRight(root);
            if (leftHeight == rightHeight) { //perfect binary tree
                return (1<<leftHeight)-1;
            }
            else return countNodes(root.left) + countNodes(root.right) + 1;
        }
        
        public int countLeft(TreeNode root) {
            int res = 0;
            while (root != null) {
                res++;
                root = root.left;
            }
            return res;
        }
        
        public int countRight(TreeNode root) {
            int res = 0;
            while (root != null) {
                res++;
                root = root.right;
            }
            return res;
        }
        
    }
    

      

  • 相关阅读:
    error: device not found
    RK3288 查看时钟树
    GPS数据包格式解析
    Android 操作文件系统失败: Read-only file system
    Ubuntu 14.04 配置安卓5.1编译环境
    升级 php composer 版本
    清理 laravel blade 模板缓存
    Laravel collection 报错 join(): Invalid arguments passed
    Laravel firstOrNew 与 firstOrCreate 的区别
    执行 crontab 的计划任务
  • 原文地址:https://www.cnblogs.com/apanda009/p/7098033.html
Copyright © 2020-2023  润新知