《剑指 Offer (第 2 版)》第 32-1 题:从上往下打印二叉树

第 32-1 题:不分行从上往下打印二叉树

传送门:不分行从上往下打印二叉树,牛客网 online judge 地址。

从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。

样例:

输入如下图所示二叉树 [8, 12, 2, null, null, 6, null, 4, null, null, null]

     8
    / \
  12  2
      /
     6
    /
  4

输出:[8, 12, 2, 6, 4]

思路:层序遍历,借助利用队列实现。其实就是层序遍历,使用的辅助的数据结构是“队列”,在遍历的过程中,注意到一些细节就可以了。在实现的过程中,要防止:

1、将空元素放入队列;
2、队列元素出队的时候,先判断队列是否为空,非空才可以出队。

Python 代码:

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def printFromTopToBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []
        queue = [root]
        res = []
        while queue:
            # 弹出队首元素,索引编号 0 不要忘记写了
            top = queue.pop(0)
            res.append(top.val)
            if top.left:
                queue.append(top.left)
            if top.right:
                queue.append(top.right)
        return res

Java 代码:

import java.util.ArrayList;
import java.util.LinkedList;

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) {
        ArrayList res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList queue = new LinkedList<>();
        queue.addLast(root);
        while (!queue.isEmpty()) {
            int curSize = queue.size();
            for (int i = 0; i < curSize; i++) {
                TreeNode curNode = queue.removeFirst();
                res.add(curNode.val);
                if (curNode.left != null) {
                    queue.addLast(curNode.left);
                }
                if (curNode.right != null) {
                    queue.addLast(curNode.right);
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode node8 = new TreeNode(8);
        TreeNode node6 = new TreeNode(6);
        TreeNode node10 = new TreeNode(10);
        TreeNode node5 = new TreeNode(5);
        TreeNode node7 = new TreeNode(7);
        TreeNode node9 = new TreeNode(9);
        TreeNode node11 = new TreeNode(11);

        node8.left = node6;
        node8.right = node10;

        node6.left = node5;
        node6.right = node7;

        node10.left = node9;
        node10.right = node11;

        Solution solution = new Solution();
        ArrayList printFromTopToBottom = solution.PrintFromTopToBottom(node8);
        System.out.println(printFromTopToBottom);
    }
}

你可能感兴趣的:(《剑指 Offer (第 2 版)》第 32-1 题:从上往下打印二叉树)