Leetcode-222題:Count Complete Tree Nodes

題目:Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

思路:如果知道一個(gè)子樹是完全二叉樹,并且其深度為h,那么這棵子樹所包含的節(jié)點(diǎn)個(gè)數(shù)便為2^h-1。否則便需遞歸求其左右子樹的節(jié)點(diǎn)個(gè)數(shù)。

代碼:

def getHightRight(self, root):
    if root == None:
        return 0
    high = 0
    while root != None:
        high += 1
        root = root.right
    return high

def getHightLeft(self, root):
    if root == None:
        return 0
    high = 0
    while root != None:
        high += 1
        root = root.left
    return high

def countNodes(self, root):
    """
    :type root: TreeNode
    :rtype: int
    """
    if root == None:
        return 0
    l_high = self.getHightLeft(root.left)
    r_high = self.getHightRight(root.right)
    if l_high == r_high:
        return 2**(l_high+1)-1
    else:
        return self.countNodes(root.left)+self.countNodes(root.right)+1
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,923評(píng)論 0 33
  • 旅行 愛上一個(gè)人就像一場(chǎng)旅行 沒有目的地 望不到終點(diǎn) 也沒有起點(diǎn) 不知不覺就愛上了 而愛上誰(shuí) 更不是自己能控制 就...
    日日晿閱讀 178評(píng)論 0 1
  • 每次提筆開始寫我都告訴自己一聲,要自由的寫作,不要條條框框,這樣文章才耐讀。 一下車走進(jìn)家門,看見欽欽抱著小孩(我...
    誰(shuí)的孤獨(dú)是一顆眼淚閱讀 404評(píng)論 0 1
  • 學(xué)插花,買花就來(lái)莎莎。 莎莎花藝專業(yè)花藝培訓(xùn),插花培訓(xùn)?;ǖ赀B鎖經(jīng)營(yíng)鮮花全國(guó)配送,專業(yè)禮儀婚慶策劃,婚禮培訓(xùn)機(jī)構(gòu)。...
    天元莎莎花藝閱讀 208評(píng)論 0 0

友情鏈接更多精彩內(nèi)容