• 二叉树的打印


    从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

    import java.util.ArrayList;
    import java.util.LinkedList;
    
     class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    public class Solution {
        ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
    
    		ArrayList<ArrayList<Integer>> level = new ArrayList<>();
    		ArrayList<Integer> arrays = new ArrayList<>();
    		LinkedList<TreeNode> queue = new LinkedList<>();
            if (pRoot == null) {
    			return level;
    		}
    		queue.add(pRoot);
    		TreeNode current = null;
    		TreeNode last = pRoot;//正在打印的当前行的最右节点
    		TreeNode nlast = null;//表示下一行的最右节点
    		while (queue.size() != 0) {
    			current = queue.poll();
    			arrays.add(current.val);
    			if (current.left != null) {
    				queue.add(current.left);
    				nlast = current.left;
    			}
    			if (current.right != null) {
    				queue.add(current.right);
    				nlast = current.right;
    			}
    			if (current == last) {
    				level.add(arrays);
    				arrays = new ArrayList<>();
    				last = nlast;
    			}
    
    		}
    		return level;
    
        }
    
    }
    
  • 相关阅读:
    Linux服务器通过rz/sz轻松上传下载文件
    Linux卸载系统自带的JDK
    汉语-词语:恒等
    汉语-词语:女人
    汉语-词语:长远
    汉语-词语:长久
    汉语-词语:短暂
    汉语-词语:当下
    汉语-词语:漫长
    中药:小麦
  • 原文地址:https://www.cnblogs.com/Onlywjy/p/7306800.html
Copyright © 2020-2023  润新知