从上往下打印二叉树

45次阅读

共计 639 个字符,预计需要花费 2 分钟才能阅读完成。

题目
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
题解
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode current = queue.poll();
TreeNode left = current.left;
TreeNode right = current.right;
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
}
result.add(current.val);
}
return result;
}
}

正文完
 0