69. Binary Tree Level Order Traversal - 二叉树的层次遍历

Description

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Example

Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
Challenge 

Challenge 1: Using only 1 queue to implement it.

Challenge 2: Use DFS algorithm to do it.

Solution

1. BFS(宽度优先搜索)

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: A Tree
     * @return: Level order a list of lists of integer
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        // write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        
        //层序遍历要用到的数据结构是queue,且java中队列实现多用LinkedList但不能用ArrayList
        Queue<TreeNode> queue = new LinkedList<TreeNode>(); 
        //add()和remove()方法在失败的时候会抛出异常(不推荐),一般使用offer()和poll()方法
        queue.offer(root);  
        
        while (!queue.isEmpty()) {
            ArrayList<Integer> level = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {    //得到每层的结果就要遍历每层,如果不需要按层分开,则可去掉这层for循环
                TreeNode head = queue.poll();   //头出队,将这个节点为根的左右节点加入队列
                level.add(head.val);
                if (head.left != null) {
                    queue.offer(head.left);
                }
                if (head.right != null) {
                    queue.offer(head.right);
                }
            }
            result.add(level);                  //每层遍历之后添加一次level到result中
        }
        return result;                          //队列为空后返回result
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值