剑指Offer第二十二题:从上往下打印二叉树

从上往下打印二叉树

https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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

解答:
思路:用队列的结构正好符合题目要求,每取出一棵子树的根节点就加入他的子节点,直到队列中没有元素,LinkedList实现了queue的接口。
public class Q_22 {

public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    if (root == null) {
        return list;
    }
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        TreeNode out = queue.poll();
        list.add(out.val);
        if (out.left != null) {
            queue.offer(out.left);
        }
        if (out.right != null) {
            queue.offer(out.right);
        }
    }
    return list;
}

}

全部评论

相关推荐

2025-12-27 22:28
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务