Binary Tree Level Order Traversal, Leetcode 解题笔记

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,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

BFS标准解法,利用一个Queue:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        if(root == null) return ret;
        LinkedList<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        ArrayList<Integer> first = new ArrayList<Integer>();
        first.add(root.val);
        ret.add(first);
        while(q.size() != 0){
            int i = 0;
            int len = q.size();
            while(i < len){
                TreeNode temp = q.poll();
                if(temp.left != null)
                    q.add(temp.left);
                if(temp.right != null)
                    q.add(temp.right);
                i++;
            }
            if(q.size() > 0){
                ArrayList<Integer> level = new ArrayList<Integer>();
                for(int index = 0; index < q.size(); index++){
                        level.add(q.get(index).val);
                }
                ret.add(level);
            }
        }
        return ret;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s