102. 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).

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

return its level order traversal as:

Solution

BFS

话说这题目跟“Binary Tree Level Order Traversal II”有实质性区别吗。。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new LinkedList();
        if (root == null) return levels;
        
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList();
            int nodesNum = queue.size();    // a snapshot representing nodes count of current level
            
            for (int i = 0; i < nodesNum; ++i) {
                TreeNode p = queue.poll();
                if (p.left != null) queue.add(p.left);
                if (p.right != null) queue.add(p.right);
                level.add(p.val);
            }
            levels.add(level);
        }
        
        return levels;
    }
}

DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levelsList = new LinkedList();
        if (root == null) return levelsList;
        levelMaker(levelsList, root, 0);
        return levelsList;
    }
    
    public void levelMaker(List<List<Integer>> levelsList, TreeNode root, int level) {
        if (root == null) return;
        if (levelsList.size() <= level) levelsList.add(new ArrayList());
        levelMaker(levelsList, root.left, level + 1);
        levelMaker(levelsList, root.right, level + 1);
        levelsList.get(level).add(root.val);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容