Prove safety offer: binary tree print multiple lines (level traversal)

1. Title Description

Printing the binary tree in layers from top to bottom, from left to right with the output layer node. Each line of output layer.

2. Ideas

Traverse the level

3. Recursion

public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        depth(pRoot, 1, list);
        return list;
    }
     
    private void depth(TreeNode root, int depth, ArrayList<ArrayList<Integer>> list) {
        if(root == null) return;
        if(depth > list.size())
            list.add(new ArrayList<Integer>());
        list.get(depth -1).add(root.val);
         
        depth(root.left, depth + 1, list);
        depth(root.right, depth + 1, list);
    }
}

4. nonrecursive

import java.util.*;

public class Solution {
    static ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        return levelorder(pRoot);
    }

    public static ArrayList<ArrayList<Integer>> levelorder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if(root == null) return result;
        queue.offer(root); //First root root enqueue 
        the while (queue.isEmpty ()!) { // Queue is not empty, the cycle 
            the ArrayList <Integer> = Node new new the ArrayList <> (); // save the value of each layer node 
            int length = queue.size (); // for each layer node number of 
            the while (length> 0 ) { 
                the TreeNode Tree = queue.poll ();
                 IF (tree.left =! null ) { 
                    Queue.offer (tree.left); 
                } 
                IF (tree.right =! null ) { 
                    Queue.offer (tree.right); 
                }
                node.add (tree.val); 
                length - ; 
            } 
            // After the cycle, the resulting layer to prepare for the next Queue, node-based layer through the results 
            result.add (Node); 
        } 
        return Result; 
    } 
}

 

Guess you like

Origin www.cnblogs.com/haimishasha/p/11520955.html