leetcode102:Binary Tree Level Order Traversal

shuaishuai3409發表於2016-05-25

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

//先摘抄一下別人的程式碼
/**
 * 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>> resultList = new ArrayList<List<Integer>>();//resultlist是陣列連結串列
        if (root == null) {
            return resultList;
        }

        List<Integer> levelStorage = new LinkedList<Integer>();//levelStorage是resultlist的代替者
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();//queue是連結串列
        queue.offer(root);//進佇列
        queue.offer(null);
        while (queue.size() > 1) {
            TreeNode top = queue.poll();//出佇列
            if (top == null) {
                resultList.add(levelStorage);
                queue.offer(null);
                levelStorage = new LinkedList<Integer>();
            } else {
                levelStorage.add(top.val);
                if (top.left != null) {
                    queue.offer(top.left);
                }
                if (top.right != null) {
                    queue.offer(top.right);
                }
            }
        }
        resultList.add(levelStorage);

        return resultList;
    }
}

相關文章