有点感动,这题在AS里写好之后复制过去一次AC了。 这种BFS的套路跟这题的一样,用queue,维护curNum和nextNum;我跟code ganker学会了这个套路,按照覃超的标准来说这代码是有点长的,但是现在已经形成记忆了,就不去修改了。思路还蛮清晰的。
public List
> levelOrderBottom(TreeNode root) { List
> res = new ArrayList<>(); if (root == null) return res; LinkedList queue = new LinkedList<>(); List cell = new ArrayList<>(); queue.add(root); int curNum = 1; int nextNum = 0; while (!queue.isEmpty()) { TreeNode node = queue.poll(); cell.add(node.val); curNum--; if (node.left != null) { queue.offer(node.left); nextNum++; } if (node.right != null) { queue.offer(node.right); nextNum++; } if (curNum == 0) { res.add(0, cell); curNum = nextNum; nextNum = 0; cell = new ArrayList<>(); } } return res; }复制代码
另
贴一下leetcode里面的人的简洁写法:https://discuss.leetcode.com/topic/7651/my-dfs-and-bfs-java-solution/2
public class Solution { public List
> levelOrderBottom(TreeNode root) { Queue queue = new LinkedList (); List
> wrapList = new LinkedList
>(); if(root == null) return wrapList; queue.offer(root); while(!queue.isEmpty()){ int levelNum = queue.size(); List subList = new LinkedList (); for(int i=0; i
递归(我没看):
public class Solution { public List
> levelOrderBottom(TreeNode root) { List
> wrapList = new LinkedList
>(); levelMaker(wrapList, root, 0); return wrapList; } public void levelMaker(List
> list, TreeNode root, int level) { if(root == null) return; if(level >= list.size()) { list.add(0, new LinkedList ()); } levelMaker(list, root.left, level+1); levelMaker(list, root.right, level+1); list.get(list.size()-level-1).add(root.val); } }复制代码