The number of nodes [LeetCode] complete binary tree

Topic links: https://leetcode-cn.com/problems/count-complete-tree-nodes

Difficulty: Moderate

Pass rate: 57.4%

Subject description:

It gives a complete binary tree , obtains the number of nodes of the tree.

Description:

Complete binary tree is defined as follows: in the binary tree, except the bottom node may not be filled, the remaining maximum number of nodes each, and the bottom layer of nodes are concentrated in a plurality of layers of the leftmost position. If the bottom of the h layer, the layer comprising the nodes 1 ~ 2h.

Example:

输入:
    1
   / \
  2   3
 / \  /
4  5 6

输出: 6

Ideas:

Violence, each node access look to see how many

Time complexity: \ (O (n-) \)

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root: return 0
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

This is not a complete binary tree can also be calculated, but did not use the nature of complete binary tree!

We can use nature, is equal to the number of nodes complete binary tree \ (^ {H} 2 -. 1 \) ,

It is, time complexity: \ (O (log (n-) ^ 2) \)

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root: return 0
        left_height = 0
        left_node = root
        right_height = 0
        right_node = root
        while left_node:
            left_node = left_node.left
            left_height += 1
        while right_node:
            right_node = right_node.right
            right_height += 1
        if left_height == right_height:
            return pow(2,left_height) - 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

Guess you like

Origin www.cnblogs.com/powercai/p/11431934.html