当前位置 博文首页 > 文章内容

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

    作者: 栏目:未分类 时间:2020-10-08 11:00:27

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    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)
        }
    }