当前位置:网站首页>【LeetCode】222. The number of nodes of a complete binary tree (2 mistakes)

【LeetCode】222. The number of nodes of a complete binary tree (2 mistakes)

2022-07-05 02:20:00 Kaimar

0
1

  • Ideas
    It's easy to think of using any traversal method to traverse all nodes . Another idea is to notice that the title says it is a complete binary tree , Then we can use its nature , That is, for a full binary tree , Its number of nodes is related to its height 2ⁿ-1, Refer to the explanation of the question Know the depth of traversing the left and right subtrees , If the depth is the same, it means that it is a full binary tree , Available formulas .
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func countNodes(root *TreeNode) int {
    
    if root == nil {
    
        return 0
    }
    queue := []*TreeNode{
    root}
    nodeCount := 0
    for len(queue) > 0 {
    
        size := len(queue)
        for i := 0; i < size; i++ {
    
            nodeCount++
            //  Value 
            node := queue[0]
            //  Out of the team 
            queue = queue[1:]

            if node.Left != nil {
    
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
    
                queue = append(queue, node.Right)
            }
        }
    }
    return nodeCount
}

2

原网站

版权声明
本文为[Kaimar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140933283628.html