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)
    }
}
posted @ 2020-10-08 10:54  ganshuoos  阅读(97)  评论(0编辑  收藏  举报