首页 > 代码库 > 【LeetCode】Binary Tree Level Order Traversal 【BFS】

【LeetCode】Binary Tree Level Order Traversal 【BFS】

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


广度优先搜索,一般做法都是采取一个队列来做。
不过这题有个比较不一样的是他返回的格式是List<List>>的格式,所以需要做一些处理。
直接上代码了,很简单的题,


JAVA CODE:

/**
 * 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>> returnList = new ArrayList<List<Integer>>();
        
        if(root == null){
            return returnList;
        }
        
        List<Integer> temp = null;

        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        queue.add( root );

        while( !queue.isEmpty() ) {
            Queue<TreeNode> tempQ = new LinkedList<TreeNode>();
            temp = new ArrayList<Integer>();
            while( !queue.isEmpty() ) {
                TreeNode tn = queue.poll();

                if( tn.left != null ) {
                    tempQ.add( tn.left );
                }
                if( tn.right != null ) {
                    tempQ.add( tn.right );
                }
                temp.add( tn.val );
            }

            queue = tempQ;
            returnList.add( temp );
        }

        return returnList;
    }
}

 






【LeetCode】Binary Tree Level Order Traversal 【BFS】