Leetcode102——Binary Tree Level Order Traversal

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

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],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

2. 求解

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

/**
 * 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;
    }
}
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/469e17e64459
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞