【部落格搬家舊文】【leetcode】515. Find Largest Value in Each Tree Row
阿新 • • 發佈:2018-11-22
注:這是我春招找實習的時候筆試某公司的原題,當時還傻傻的不太會做。
//廣度優先搜尋就可以實現二叉樹每一層的遍歷,通常都用佇列來實現。佇列儲存未被檢測的結點,結點按寬度優先的次序被訪問和進出佇列。 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { publicList<Integer> largestValues(TreeNode root) { Queue<TreeNode> queue=new LinkedList<>(); List<Integer> list=new ArrayList<>(); queue.add(root); int queueSize=root== null ? 0:1; while(queueSize > 0){ int max=Integer.MIN_VALUE;for(int i=0; i< queueSize; i++){ TreeNode n=queue.poll(); if(n.val > max) max=n.val; if(n.left != null) queue.add(n.left); if(n.right != null) queue.add(n.right); } list.add(max); queueSize=queue.size(); } return list; } }
//以下是關於深度優先搜尋和廣度優先搜尋的一個小結 //DFS:深度優先搜尋,一直往深處走,直到找不到解為止 DFS(dep,.....) //dep表示當前深度 { if(找到解了 || 走不下去了){ ........ return; } 列舉下一種情況,dep+1 } //BFS:廣度優先搜尋,通常用佇列來實現,如本題。 初始化佇列Queue Q={root} while(Q非空){ 取佇列Q隊首元素u,u出隊; if( u == 目標狀態){ .... } 將所有與u相鄰且未被訪問的結點進入佇列; 標記u為已訪問; } //DFS使用棧來儲存未被檢測的結點,按照深度優先的次序被訪問並依次壓入棧中,反序出棧進行新的檢測 //BFS使用佇列儲存未被檢測的結點,結點按照寬度優先的次序被訪問和進出佇列