69. 二叉树的层次遍历

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

样例

样例 1:

输入:{1,2,3}
输出:[[1],[2,3]]
解释:
   1
  / \
 2   3
它将被序列化为{1,2,3}
层次遍历

样例 2:

输入:{1,#,2,3}
输出:[[1],[2],[3]]
解释:
1
 \
  2
 /
3
它将被序列化为{1,#,2,3}
层次遍历

挑战

挑战1:只使用一个队列去实现它

挑战2:用BFS算法来做

注意事项

  • 首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
  • 节点数量不超过20。

输入测试数据 (每行一个参数)如何理解测试数据?

 

/**
 * 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>> list =new ArrayList<List<Integer>>();
        if (root==null){
            return list;
        }
        
        Queue<TreeNode> queue =new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
           ArrayList<Integer> level = new ArrayList();
           int size = queue.size();   // 能将同一层的节点放到一个list中的要点
           for(int i=0;i<size;i++){
              TreeNode temp = queue.poll();;
              level.add(temp.val);
              if(temp.left !=null)
                  queue.offer(temp.left);
              if(temp.right !=null)
                  queue.offer(temp.right);
           }
          list.add(level);
        }
    return list;
    }
}

 

输入

查看差别

{1,2,3}

输出

[[1],[2,3]]

期望答案

[[1],[2,3]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值