Binary Tree Level Order Traversal

Binary Tree Level Order Traversal

问题:

  Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

思路:

  bfs

我的代码:

public class Solution {

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> rst = new ArrayList<List<Integer>>();

        if(root == null) return rst;

        

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

        queue.offer(root);

        while(!queue.isEmpty())

        {

            int size = queue.size();

            List<Integer> list = new ArrayList<Integer>();

            for(int i = 0; i < size; 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);

            }

            rst.add(list);

        }

        // Collections.reverse(rst);

        return rst;

    }

}
View Code

 

你可能感兴趣的:(binary)