Thursday, June 12, 2014

Leetcode: Binary Tree Level Order Traversal

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

Solution:

/**
 * Definition for binary tree
 * 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>> solution = new ArrayList<List<Integer>>();
        if (root == null)
            return solution;
        List<TreeNode> actualList = new ArrayList<TreeNode>();
        actualList.add(root);
        while(!actualList.isEmpty())
        {
            ArrayList<Integer> thisLevel = new ArrayList<Integer>();
            List<TreeNode> nextList = new ArrayList<TreeNode>();
            for(TreeNode temp: actualList)
            {
                thisLevel.add(temp.val);
                if(temp.left!=null)
                    nextList.add(temp.left);
                if(temp.right!=null)
                    nextList.add(temp.right);
            }
            solution.add(thisLevel);
            actualList = nextList;
        }
        return solution;
    }
}

No comments :

Post a Comment