LeetCodeBinary Tree Level Order Traversal BFS

Posted hdw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCodeBinary 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;
    }
}

 




















以上是关于LeetCodeBinary Tree Level Order Traversal BFS的主要内容,如果未能解决你的问题,请参考以下文章

leetcodeBinary Tree Level Order Traversal

LeetcodeBinary Tree Maximum Path Sum

leetcodebinary-tree-maximum-path-sum

[Leetcode] Binary Tree Level Order Traversal

[leetcode tree]103. Binary Tree Zigzag Level Order Traversal

102. Binary Tree Level Order Traversal