前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Binary Tree Level Order Traversal

Binary Tree Level Order Traversal

作者头像
Tyan
发布2019-05-25 23:13:18
2890
发布2019-05-25 23:13:18
举报
文章被收录于专栏:SnailTyan

1. 问题描述

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

For example: Given binary tree [3,9,20,null,null,15,7],

代码语言:javascript
复制
    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

代码语言:javascript
复制
[
  [3],
  [9,20],
  [15,7]
]

2. 求解

这个题就是一个树的层次遍历问题,需要用到新的数据结构队列,把每一层的结点的子结点放入到队列中,依次遍历。

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        if(root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        Queue<TreeNode> result = new LinkedList<TreeNode>();
        List<Integer> level = new ArrayList<Integer>();
        while(!queue.isEmpty()) {
            TreeNode temp = queue.poll();
            level.add(temp.val);
            if(temp.left != null) {
                result.add(temp.left);
            }
            if(temp.right != null) {
                result.add(temp.right);
            }
            if(queue.isEmpty()) {
                queue = result;
                result = new LinkedList<TreeNode>();
                list.add(level);
                level = new ArrayList<Integer>();
            }
        }
        return list;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年03月22日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 问题描述
  • 2. 求解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档