注:这是我春招找实习的时候笔试某公司的原题,当时还傻傻的不太会做。
//广度优先搜索就可以实现二叉树每一层的遍历,通常都用队列来实现。队列保存未被检测的结点,结点按宽度优先的次序被访问和进出队列。 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<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使用队列保存未被检测的结点,结点按照宽度优先的次序被访问和进出队列