leetcode -. 222 complete binary number of nodes

Violence:

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        else:
            return 1+self.countNodes(root.left)+self.countNodes(root.right)
When execution: 92 ms, beat the 85.10% of users in all python3 submission
Memory consumption: 21.6 MB, beat the 5.26% of users in all python3 submission
 
 
The nature of the use of complete binary tree:
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)
When execution: 80 ms, beat the 98.16% of users in all python3 submission
Memory consumption: 21.3 MB, beat the 5.26% of users in all python3 submission
 
——2019.11.19

Guess you like

Origin www.cnblogs.com/taoyuxin/p/11889996.html