Finger Offer 32-i. Print binary tree from top to bottom



java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }} * * /
class Solution {

    public int[] levelOrder(TreeNode root) {
        if(root == null) return new int[0];
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<Integer> res =  new ArrayList<>(); 
       return forEacher( root,queue ,res);

    }
    int[] forEacher(TreeNode root,Queue<TreeNode> queue ,ArrayList<Integer> res){
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode tmp = queue.poll();
            res.add(tmp.val);
            if(tmp.left! =null)queue.add(tmp.left);
            if(tmp.right! =null)queue.add(tmp.right);
        }
        int[] d = new int[res.size()];
        for(int i = 0; i<res.size(); i++){ d[i] = res.get(i); }returnd; }}Copy the code

Finger Offer 32-ii. Print binary tree II from top to bottom



java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }} * * /
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res =  new ArrayList<>(); 
        if(root ! = null)queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> node = new ArrayList<>();
            for(int i=queue.size(); i>0; i--){ TreeNode tmp =queue.poll();
                node.add(tmp.val);
                if(tmp.left! =null)queue.add(tmp.left);
                if(tmp.right! =null)queue.add(tmp.right);
            }
            res.add(node);
            
        }
        returnres; }}Copy the code

Finger Offer 32-iii. Print binary tree III from top to bottom



java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }} * * /
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res =  new ArrayList<>(); 
        if(root ! = null)queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> node = new ArrayList<>();
            for(int i=queue.size(); i>0; i--){ TreeNode tmp =queue.poll();
                node.add(tmp.val);
                if(tmp.left! =null)queue.add(tmp.left);
                if(tmp.right! =null)queue.add(tmp.right);
            }
            res.add(node);
            
        }
        returnres; }}Copy the code