剑指Offer—二叉树分层打印

剑指Offer—二叉树分层打印

题目

解题思路:建立一个队列,存放结点,创建两个指针指向最近结点和行尾结点

/**
 * 分层遍历二叉树(使用队列实现)
 * 1、新建队列,且创建两个临时节点元素last和nlast,初始值均为头结点,栈顶元素压入队列
 * 2、循环遍历队列,如果不为空,队头元素出队赋值给node,并打印
 *      如果队头元素存在左孩子,左孩子入队,左孩子赋值给nlast。
 *      如果队头元素存在右孩子,右孩子入队,右孩子赋值给nlast
 *      如果队头元素等于last,换行并打印行号,把nlast赋给last.
 * 3、直至队列为空
 * @param root  头结点
 */
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
    ArrayList<Integer> rs = new ArrayList<>();
    LinkedList<TreeNode> queue = new LinkedList<>();

    TreeNode node = null;
    TreeNode last = root,nlast = root;

    if (root!=null){
        queue.offer(root);
    }
    while (!queue.isEmpty()){
        node = queue.poll();
        rs.add(node.val);
        if (node.left!=null){
            queue.offer(node.left);
            nlast = node.left;
        }
        if (node.right!=null){
            queue.offer(node.right);
            nlast = node.right;
        }
        if (node == last){
            last = nlast;
        }
    }
    return rs;
}

猜你喜欢

转载自blog.csdn.net/hnuwyd/article/details/80353731