1. 程式人生 > >222. 完全二叉樹的節點個數(中等、樹)

222. 完全二叉樹的節點個數(中等、樹)

 給出一個完全二叉樹,求出該樹的節點個數。

說明:

完全二叉樹的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層為第 h 層,則該層包含 1~ 2h 個節點。

示例:

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

輸出: 6
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

超出了時間的限制

思路:利用完全二叉樹的性質,加上一點數學的方法,只計算一棵樹的節點數

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def get_depth(root):  #計算一棵完全二叉樹的深度
            result=0
            while root:
                root=root.left
                result+=1
            return result
        if not root:
            return 0
        l=get_depth(root.left)
        r=get_depth(root.right)
        if l==r:
            return pow(2,l)+self.countNodes(root.right)
        if l!=r:
            return pow(2,r)+self.countNodes(root.left)
        #pow() 方法返回 x的y次方的值
        #根是第0層
        

執行用時: 136 ms, 在Count Complete Tree Nodes的Python3提交中擊敗了85.07% 的使用者