广度优先搜索_广度优先搜索(BFS)
生活随笔
收集整理的這篇文章主要介紹了
广度优先搜索_广度优先搜索(BFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
廣度優先搜索(breadth-first search)可用于“圖”這種數據結構中,查找最短路徑。
樹是一種特殊的圖,二叉樹是一種特殊的樹。廣度優先搜索常用于遍歷二叉樹,在這個遍歷的過程中,需要用到隊列這一先進先出(FIFO)的數據結構。
Queue<Node> queue = new LinkedList<>();廣度優先搜索是層級遍歷,它依次遍歷每一層的節點,并將該層所有節點的子節點添加到隊列中,進行下一次遍歷,直到遍歷結束,隊列為空。
559. Maximum Depth of N-ary Tree
Loading...?leetcode.com給定一個樹,找出這個樹的最大深度。
class Solution {public int maxDepth(Node root) {if(root == null){return 0;}int maxDepth = 0;//用于記錄最大深度Queue<Node> queue = new LinkedList<>();//隊列queue.add(root);while(!queue.isEmpty())//直到隊列為空,即,遍歷完所有的節點{maxDepth++;//每遍歷一層,計數+1int size = queue.size();//當前層節點的個數for(int i = 0; i < size; i++){Node node = queue.poll();//poll()方法,取出隊首節點if(node.children != null)//如果存在子節點,需要將子節點依次添加到隊列中,用于下一層遍歷{List<Node> children = node.children;for(Node child : children){queue.add(child);}}}}return maxDepth;} }111. Minimum Depth of Binary Tree
Loading...?leetcode.com給定一個二叉樹,求出該二叉樹的最小深度(沒有子節點的節點,距離根節點的最小距離)。
class Solution {/*** 解法:BFS,遍歷每一層,找出第一個沒有左右子節點的節點,返回即可。*/public int minDepth(TreeNode root) {if(root == null){return 0;}int minDepth = 0;Queue<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()){int size = queue.size();minDepth++;for(int i = 0; i < size; i++){TreeNode node = queue.poll();if(node.left == null && node.right == null)//該節點沒有子節點{return minDepth;}if(node.left != null)//左子節點不為空,添加到隊列,進行下一層循環{queue.add(node.left);}if(node.right != null)//右子節點不為空,添加到隊列,進行下一層循環{queue.add(node.right);}}}return minDepth;} }總結
以上是生活随笔為你收集整理的广度优先搜索_广度优先搜索(BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 显示数据库数据tk_如何使
- 下一篇: 非确定性算法_使用最坏情况提高基于MPC