[Offer] [32-1] [not] binary tree branches are printed upside down

Title Description

  Top to bottom printing each node of the binary tree, the nodes in the same layer in order from left to right printing. For example, the input binary tree diagram, the 8,6,10,5,7,9,11 sequentially printed out. Binary tree node is defined as follows:
  
  

Cattle brush off questions address network

Ideas analysis

  It is actually a binary tree traverse the level , achieved through queue

Test Case

  1. Functional Test: complete binary tree; all nodes in the left subtree only binary tree; all nodes in the right subtree only binary tree.
  2. Special input test: binary tree root pointer is nullptr; only one node of the binary tree.

Java code

public class Offer32 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

    public static  ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        return Solution1(root);
    }

    private static ArrayList<Integer> Solution1(TreeNode root) {
         LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            ArrayList<Integer> list = new ArrayList<Integer>();
            if(root==null){
                return list;
            }
            queue.offer(root);
            TreeNode node = null;
            while(queue.size()!=0){
                node = queue.poll();
                list.add(node.val);
                if(node.left!=null){
                   queue.offer(node.left);
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }
      
            }
            return list;
    }

    private static void test1() {

    }

    private static void test2() {

    }

    private static void test3() {
    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer321-bu-fen-xing-cong-shang-dao-xia-da-yin-er-.html