首页 > 试题广场 >

完全二叉树结点数

[编程题]完全二叉树结点数
  • 热度指数:10307 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一棵完全二叉树的头节点head,返回这棵树的节点个数。

完全二叉树指:设二叉树的深度为h,则 [1,h-1] 层的节点数都满足 

数据范围:节点数量满足 ,节点上每个值都满足
进阶:空间复杂度  , 时间复杂度
示例1

输入

{1,2,3} 

输出

3
示例2

输入

{}

输出

0

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 
 * @param head TreeNode类 
 * @return int整型
*/
func nodeNum( head *TreeNode ) int {
    ans:=0
    var order func(*TreeNode)
    order=func(root *TreeNode){
        if root==nil{
            return
        }
        ans++
        order(root.Left)
        order(root.Right)
    }
    order(head)
    return ans
}

发表于 2023-03-09 00:01:24 回复(0)
package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 
 * @param head TreeNode类 
 * @return int整型
*/
var res int
func nodeNum( head *TreeNode ) int {
    res = 0
    nodeNumCore(head)
    return res
}

func nodeNumCore(head *TreeNode) {
    search(head)
}

func search(head *TreeNode)  {
    if head != nil {
        res++
        nodeNumCore(head.Left)
        nodeNumCore((head.Right))
    }
}
发表于 2021-08-14 11:23:42 回复(0)

问题信息

难度:
2条回答 8705浏览

热门推荐

通过挑战的用户

查看代码