码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal

时间:2017-03-15 12:02:14      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:material   tar   ==   this   lis   ++   public   bfs   .net   

Very useful basic study material:   http://blog.csdn.net/raphealguo/article/details/7523411

1. BFS

The hard part is to define the level. Using int size = queue.size(); to control it.

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        // write your code here
        ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
        if (root == null) {
            return rst;        
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            ArrayList<Integer> level = new ArrayList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++){
                TreeNode cur = queue.poll();
                level.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }    
            }
            rst.add(level);
        }
        return rst;
    }
}

 

Binary Tree Level Order Traversal

标签:material   tar   ==   this   lis   ++   public   bfs   .net   

原文地址:http://www.cnblogs.com/codingEskimo/p/6553038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!