Leecode107:层序遍历,从叶子节点到根节点
正常的层序遍历之后,对resList进行反转,调用Collections.reverse(resList);或者每次添加list时,从resList的头部开始添加
class Solution { public List<List<Integer>> resList = new ArrayList<List<Integer>>(); public List<List<Integer>> levelOrderBottom(TreeNode root) { checkfun(root); return resList; } public void checkfun(TreeNode root){ if(root == null) return; Queue<TreeNode> que = new LinkedList<TreeNode>(); que.offer(root); while(!que.isEmpty()){ List<Integer> list = new ArrayList<Integer>(); int len = que.size(); while(len > 0) { TreeNode node = que.poll(); list.add(node.val); if(node.left != null) {que.offer(node.left);} if(node.right != null) {que.offer(node.right);} len--; } resList.add(0,list);//Collections.reverse(resList); } } }
Leecode 199二叉树的右视图
思路:层序遍历,每层只保留最后一个数,即判断len =1时,将val添加到list中。同理左视树,可以len = qun.size()得到。
class Solution { List<Integer> list = new ArrayList<Integer>(); public List<Integer> rightSideView(TreeNode root) { checkfun(root); return list; } public void checkfun(TreeNode root){ if(root == null) return; Queue<TreeNode> que = new LinkedList<TreeNode>(); que.offer(root); while(!que.isEmpty()){ int len = que.size(); while(len > 0) { TreeNode node = que.poll(); if(len == 1){list.add(node.val);} if(node.left != null) {que.offer(node.left);} if(node.right != null) {que.offer(node.right);} len--; } } } }
标签:总结,node,list,len,Leecode,que,二叉树,resList,root From: https://www.cnblogs.com/noedaydayup/p/16739995.html