Leetcode - 廣度優先演算法專題__演算法

來源:互聯網
上載者:User
> 基礎

1. 廣度遍曆優先是從給定的root節點開始,逐層次的向下訪問各個節點;

2. 實現的方式是通過隊列的先進先出,將從root節點開始的左孩子和右孩子壓入到隊列中,並順序取出;

3. 由於是用隊列實現,因此不存在用遞迴實現的方式。


下面是基本的廣度遍曆優先演算法:

def breadthFirstSearch(root):    queue = []    queue.append(root)    while queue:        node = queue[0]        queue.pop(0)        print ('%d ' % node.data)        if node.left:            queue.append(node.left)        if node.right:            queue.append(node.right)

> Leetcode - 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]]
Note:這是一道二叉樹的廣度優先遍曆練習題,不同之處在於要分辨出每個Node所在的深度,並給出每個深度所有Node的集合。解題思路有兩種,一種是使用兩個隊列,分別為主隊列和副隊列,迴圈主隊列裡的所有節點,並把所有的孩子放在副隊列中。這樣當主隊列為空白時,把副隊列賦給主隊列,並清空副隊列,就進入到下一級深度的迴圈。還有一種是使用flag,在root結點後加入flag,然後每次訪問到flag的時候,就意味著訪問到了該深度所有的Node,並且下一個深度的所有Node都加入到了隊列中,這時再加入一個flag,依此迴圈。這裡使用第二種方法。

Answer:

def levelOrder(root):    if root is []:        return []    flag = TreeNode(65536)    queue, line, res = [], [], []    queue.append(root)    queue.append(flag)    while queue:        node = queue[0]        queue.pop(0)        if node.val is not 65536:            line.append(node.val)            if node.left:                queue.append(node.left)            if node.right:                queue.append(node.right)        else:            res.append(line)            if not queue:                return res            queue.append(flag)            line = []

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.