从上往下打印出二叉树的每个节点,同层节点从左至右打印。 java

时间:2021-12-04 17:29:32





从上往下打印出二叉树的每个节点,同层节点从左至右打印。



public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
		ArrayList<Integer>  arrayList = new ArrayList<Integer>();
		ArrayList<TreeNode>  list = new ArrayList<TreeNode>();
		if (root == null) {
			return null;
		}
		list.add(root);
		while(list.size() >0){
			for (int i = 0; i < list.size(); i++) {
				arrayList.add(list.get(i).val);
			}
			list = getList(list);
		}
		return arrayList;
    }
	
	
	public static ArrayList<TreeNode> getList(ArrayList<TreeNode> list){
		ArrayList<TreeNode> newList = new ArrayList<TreeNode>();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).left != null) {
				newList.add(list.get(i).left);
			}
			if (list.get(i).right != null) {
				newList.add(list.get(i).right);
			}
		}
		return newList;
	}