zoukankan      html  css  js  c++  java
  • leetcode刷题笔记 222题 完全二叉树的节点个数

    leetcode刷题笔记 222题 完全二叉树的节点个数

    源地址:222. 完全二叉树的节点个数

    问题描述:

    给出一个完全二叉树,求出该树的节点个数。

    说明:

    完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

    示例:

    输入:
    1
    /
    2 3
    / /
    4 5 6

    输出: 6

    //使用递归,遍历所有节点
    /**
     * Definition for a binary tree node.
     * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
     *   var value: Int = _value
     *   var left: TreeNode = _left
     *   var right: TreeNode = _right
     * }
     */
    object Solution {
        def countNodes(root: TreeNode): Int = {
            var count = 0
            def helper(root: TreeNode): Unit = {
                if (root != null) count += 1
                if (root == null) return 
                if (root.left != null) helper(root.left)
                if (root.right != null) helper(root.right)
            }
            helper(root)
            return count
        }
    }
    
    //使用二分思想,基于完全二叉树性质
    //对左右子树进行计算, 若高度一致,则说明左子树完全二叉树,需要对右侧统计
    //反之,右子树满,需要对左子树统计
    /**
     * Definition for a binary tree node.
     * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
     *   var value: Int = _value
     *   var left: TreeNode = _left
     *   var right: TreeNode = _right
     * }
     */
    object Solution {
        def countNodes(root: TreeNode): Int = {
            def getHeight(root: TreeNode): Int = {
                var height = 0
                var temp =root
                while (temp != null) {
                    height += 1
                    temp = temp.left
                }
                return height
            }
            
            if (root == null) return 0
            val lHeight = getHeight(root.left)
            val rHeight = getHeight(root.right)
            
            if (lHeight == rHeight) return math.pow(2, lHeight).toInt + countNodes(root.right)
            else return math.pow(2,rHeight).toInt + countNodes(root.left)
        }
    }
    
  • 相关阅读:
    HTML5中表单的创建
    防冲撞协议原理实验报告
    yii2.0 Activeform表单部分组件使用方法 [ 2.0 版本 ]
    Yii正则验证
    Yii2用Gii自动生成Module+Model+CRUD
    yii2框架安装运行init.bat报错php.exe不是内部或外部命令
    YII2.0安装教程,数据库配置前后台 [ 2.0 版本 ]
    ignore_user_abort函数制定计划任务
    php 常用的系统函数
    php常用字符串处理函数
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13780590.html
Copyright © 2011-2022 走看看