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)
        }
    }
    
  • 相关阅读:
    Vue中data数据,使用v-model属性绑定第三方插件(例如Jquery的日期插件)无法自动更新
    Mybatis的XML文件调用静态方法
    将博客搬至CSDN
    深入理解Java:类加载机制及反射
    JDBC中Statement与PreparedStatement的区别
    响应实体类
    MD5加密
    idea的注入和自动编译配置
    mybatis三剑客之插件---MyBatis plugins
    通过git从码云克隆项目到本地
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13780590.html
Copyright © 2011-2022 走看看