Binary Tree Level Order Traversal

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;
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券