美文网首页
Binary Tree Level Order Traversa

Binary Tree Level Order Traversa

作者: tracy_668 | 来源:发表于2019-01-21 12:18 被阅读2次

    原题链接

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

        3
       / \
      9  20
        /  \
       15   7
    

    return its level order traversal as:
    [
    [3],
    [9,20],
    [15,7]
    ]

    思路分析

    • 这里是层次遍历,层次遍历应该使用先进先去的队列数据结构,这里还需要记录每层的节点数目。
     public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> ret = new ArrayList<>();
            if (root == null) {
                return ret;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int levelCount = queue.size();
                List<Integer> list = new ArrayList<>();
                for (int i = 0; i < levelCount; i++) {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    } 
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                    
                }
                ret.add(list);
            }
            return ret;
        }
    

    相关文章

      网友评论

          本文标题:Binary Tree Level Order Traversa

          本文链接:https://www.haomeiwen.com/subject/ovkccqtx.html