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)
        }
    }
    
  • 相关阅读:
    kubadm初始化找不到镜像
    ssh登录等待时间长问题
    6.vue之v-html
    5.vue之v-text
    4.vue之data对象
    3.vue之el:挂载点
    2.vue基础test
    1.vue之软件VSCode(自动刷新)
    java计算金额保留两位小数精确到分(四舍六入五成双)
    win7 64位 旗舰版装系统记录及window简记
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13780590.html
Copyright © 2011-2022 走看看