69. 二叉树的层次遍历

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例

给一棵二叉树 {3,9,20,#,#,15,7} :

  3
 / \
9  20
  /  \
 15   7

返回他的分层遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

代码

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import LintClass.TreeNode;

/**
 * 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 LevelOrder_69 {
    /*
     * @param root: A Tree
     * @return: Level order a list of lists of integer
     */
    public List> levelOrder(TreeNode root) {
        // write your code here
        if(root == null)
            return null;    
        
        List> output = new ArrayList>();
        LinkedList queue = new LinkedList();
        queue.add(root);
        TreeNode temp = null;
        while (!queue.isEmpty()) {
            ArrayList resultArray = new ArrayList();
            int size = queue.size();
            for(int i = 0; i < size; i++){
                temp = queue.poll();
                resultArray.add(temp.val);
                if (temp.left != null) {
                    queue.add(temp.left);
                }
                if (temp.right != null) {
                    queue.add(temp.right);
                }
            }
            output.add(resultArray);
        }
        
        return output;
    }
    
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode root_1_left = new TreeNode(9);
        TreeNode root_1_right = new TreeNode(20);
        TreeNode root_2_left = new TreeNode(15);
        TreeNode root_2_right = new TreeNode(7);
        root.left = root_1_left;
        root.right = root_1_right;
        root.right.left = root_2_left;
        root.right.right = root_2_right;
        LevelOrder_69 obj = new LevelOrder_69();
        System.out.print(obj.levelOrder(root));
    }
}

你可能感兴趣的:(69. 二叉树的层次遍历)