This action will force synchronization from wangjili/Algorithm, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
package part7tree;import java.util.ArrayList;import java.util.LinkedList;import java.util.Queue;/*** Created by Dell on 2017年07月27日.*/public class TreePrinter {//层次打印,每一行存一个数组public int[][] printTree(TreeNode root) {if(root==null)return null;Queue<TreeNode> stack=new LinkedList<TreeNode>() ;stack.add(root);ArrayList<ArrayList<Integer>> lists=new ArrayList<ArrayList<Integer>>();//记录下最右的结点TreeNode last=root,right=null,cur=null;//last是本层的最右,right是更新统计下一层的最右ArrayList<Integer> curlist=null;while(!stack.isEmpty()){//什么时候判断是否最右cur=stack.poll();//添加到对应的curlist中if(curlist==null){curlist=new ArrayList<Integer>();}curlist.add(cur.val);//将该节点的子节点添加到Stack中,并维护right的值if(cur.left!=null){stack.add(cur.left);right=cur.left;}if(cur.right!=null){stack.add(cur.right);right=cur.right;}//根据last判断curlist的提交和更新,last和rightif(cur==last){//说明已经到了尾部lists.add(curlist);curlist=null;last=right;}}int[][] res=new int[lists.size()][];int i=0,j=0;for(ArrayList<Integer> list:lists){res[i]=new int[list.size()];for(Integer num:list){res[i][j++]=num;}i++;j=0;}return res;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。