102. Binary Tree Level Order Traversal [easy] (Python)__Python

來源:互聯網
上載者:User
題目連結

https://leetcode.com/problems/binary-tree-level-order-traversal/ 題目原文

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its level order traversal as:

[  [3],  [9,20],  [15,7]]
題目翻譯

給定一個二叉樹,返回所有節點值的層序遍曆結果。(從左至右,從上到下遍曆)
比如,給出二叉樹:{3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

它的層序遍曆結果為:

[  [3],  [9,20],  [15,7]]
思路方法 思路一

層序遍曆的一般想法,做廣度優先遍曆(BFS)。遍曆的同時,注意記錄遍曆結果要用滿足題目要求的輸出格式。

代碼

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def levelOrder(self, root):        """        :type root: TreeNode        :rtype: List[List[int]]        """        res = []        if root == None:            return res        q = [root]        while len(q) != 0:            res.append([node.val for node in q])            new_q = []            for node in q:                if node.left:                    new_q.append(node.left)                if node.right:                    new_q.append(node.right)            q = new_q        return res
思路二

用深度優先搜尋(DFS),節點的深度與輸出結果數組的下標相對應。注意在遞迴的時候要儲存每次訪問的節點值。

代碼

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def levelOrder(self, root):        """        :type root: TreeNode        :rtype: List[List[int]]        """        res = []        self.dfs(root, 0, res)        return res    def dfs(self, root, depth, res):        if root == None:            return res        if len(res) < depth+1:            res.append([])        res[depth].append(root.val)        self.dfs(root.left, depth+1, res)        self.dfs(root.right, depth+1, res)

PS: 新手刷LeetCode,新手寫部落格,寫錯了或者寫的不清楚還請幫忙指出,謝謝。
轉載請註明:http://blog.csdn.net/coder_orz/article/details/51363095

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.