Day22 剑指offer:打印二叉树

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

import java.util.ArrayList;
import java.util.Queue;
import java.util.ArrayDeque;
import java.util.LinkedList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList PrintFromTopToBottom(TreeNode root) {
        Queue deque = new LinkedList();
        ArrayList res = new ArrayList();
        if(root == null) return res;
        deque.add(root);
        while(!deque.isEmpty()){
            TreeNode node = deque.remove();
            res.add(node.val);
            if(node.left != null){
                deque.add(node.left);
            }
            if(node.right != null){
                deque.add(node.right);
            }
        }
        return res;
    }
}

你可能感兴趣的:(Day22 剑指offer:打印二叉树)