• 二叉树的打印


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

    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;
    
        }
    
    }
    
  • 相关阅读:
    RAID、LVM和btrfs文件系统
    RAID、LVM和btrfs文件系统
    python实现二分叉查找
    python实现二分叉查找
    python实现二分叉查找
    python实现二分叉查找
    java集合的简单用法
    java集合的简单用法
    java集合的简单用法
    用 AJAX 读取xml 节点属性值
  • 原文地址:https://www.cnblogs.com/Onlywjy/p/7306800.html
Copyright © 2020-2023  润新知