List[List[int]]:list=[]ifrootisNone:returnlistqueue=[root]whilequeue:cur=[]foriinrange" />

日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

(面試)打印二叉樹的所有最右節(jié)點(diǎn)--python

系統(tǒng) 2338 0

? ? ? ?打印二叉樹最右側(cè)節(jié)點(diǎn)其實(shí)是改自二叉樹的層次遍歷,多了一步,即輸出每一層的末尾節(jié)點(diǎn)。如下題,輸出最右側(cè)節(jié)點(diǎn)結(jié)果應(yīng)為 [3,20,7]。

(面試)打印二叉樹的所有最右節(jié)點(diǎn)--python_第1張圖片

首先看二叉樹的層次遍歷,使用隊(duì)列(queue)來存儲(chǔ)二叉樹的節(jié)點(diǎn),

(面試)打印二叉樹的所有最右節(jié)點(diǎn)--python_第2張圖片 ?? (面試)打印二叉樹的所有最右節(jié)點(diǎn)--python_第3張圖片 ? ?

(面試)打印二叉樹的所有最右節(jié)點(diǎn)--python_第4張圖片

具體代碼層次遍歷實(shí)現(xiàn):

            
              def levelOrder(self, root: TreeNode) -> List[List[int]]:
        list = []
        if root is None:return list
        queue = [root]
        while queue:
            cur = []
            for i in range(len(queue)):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                cur.append(node.val)
            list.append(cur)
        return list
            
          

?打印出二叉樹最右側(cè)節(jié)點(diǎn):

            
                  # 打印二叉樹最右節(jié)點(diǎn)
    def printRightNode(self, root):
        queue = [root]
        list = []
        while queue:
            res = []
            # 控制二叉樹每層的節(jié)點(diǎn)
            for i in range(len(queue)):
                node = queue.pop(0)
                if node.lchild:
                    queue.append(node.lchild)
                if node.rchild:
                    queue.append(node.rchild)
                res.append(node.key)
            list.append(res)
        ans = []
        for i in list:
            # 取每層最后一個(gè)節(jié)點(diǎn)即為最右節(jié)點(diǎn)
            ans.append(i[-1])
        print(ans)
            
          

?


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會(huì)非常 感謝您的哦!??!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 泰顺县| 新民市| 乌审旗| 治多县| 西平县| 西吉县| 苏尼特左旗| 罗定市| 昂仁县| 阿城市| 乌拉特中旗| 屯昌县| 平塘县| 平阴县| 团风县| 平潭县| 延寿县| 永靖县| 西峡县| 龙井市| 鹤庆县| 濮阳市| 绥化市| 察隅县| 昔阳县| 铜川市| 巴林左旗| 合作市| 邯郸县| 秭归县| 长寿区| 三河市| 图们市| 蓝山县| 临沧市| 察隅县| 嵩明县| 任丘市| 平谷区| 兴城市| 天长市|