Leetcode 102. Binary Tree Level Order Traversal 基本层次遍历

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

层次遍历

本题是最基本的层次遍历问题,不做赘述。

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<TreeNode> queue = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root==null) return result;
        queue.add(root);
        int direct = 0;
        while (!queue.isEmpty()){
            List<Integer> addi = new ArrayList<>();
            int num = queue.size();
            for (int i=0;i<num;i++){
                TreeNode node = queue.remove(0);
                addi.add(node.val);
                if (node.left!=null) queue.add(node.left);
                if (node.right!=null) queue.add(node.right);
            }
            result.add(addi);
        }
        return result;
    }
}


1 thought on “Leetcode 102. Binary Tree Level Order Traversal 基本层次遍历”

  • I don’t even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *