leetCode练习(102)

题目:Binary Tree Level Order Traversal

难度:easy

问题描述:

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


解题思路:按层输出二叉树的所有元素。广度搜索(BFS)的基本题型。基本方法是构造一个储存节点的队列queue,存入根节点root(3),进行BFS时,提出这一层的节点3,再载入3的子节点9和20。此层搜索结束。进入下一层BFS,提出9,输入null,提出20,输入15,7。第二层结束。。。以此循环,直到队列为空结束。

代码如下:

/**
 * 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> levelOrder(TreeNode root) {
        List> res=new ArrayList<>();
        Queue queue=new LinkedList<>();
        if(root==null){
        	return res;
        }
        queue.add(root);
        bfs(res,queue);
        return res;
    }
    private void bfs(List> res,Queue queue){
    	int len=queue.size();
    	if(len==0){
    	    return;
    	}
    	TreeNode t;
    	List list=new ArrayList<>();
    	for(int i=0;i

你可能感兴趣的:(leetCode)