第22题——从上往下打印出二叉树

105 阅读1分钟

题目:

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

思路:

就是层次遍历 Java

package nowcoder;

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

public class S22_PrintFromTopToBottom {
    public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if (root == null) return list;
        queue.offer(root);
        TreeNode out;
        while (!queue.isEmpty()) {
            out = queue.poll();
            list.add(out.val);
            if (out.left != null) queue.offer(out.left);
            if (out.right != null) queue.offer(out.right);
        }
        return list;
    }
    public static void main(String[] args){
        S22_PrintFromTopToBottom s22 = new S22_PrintFromTopToBottom();
        Integer[] array = {1, 2, 3, 9, 8, 7, 6, 5, 4};
        PrintTreeLayer p = new PrintTreeLayer();
        TreeNode root = p.arrayToTree(array, 0);
        System.out.println(s22.printFromTopToBottom(root));
    }
}

Python

import queue
from PrintTreeLayer import PrintTreeLayer
class PrintFromTopToBottom:
    def printFromTopToBottom(self, root):
        if not root:
            return None
        que = queue.Queue()
        que.put(root)
        list = []
        while que.qsize() != 0:
            out = que.get()
            list.append(out.val)
            if out.left: que.put(out.left)
            if out.right: que.put(out.right)
        return list
if __name__ == '__main__':
    test = PrintFromTopToBottom()
    array = [1, 2, 3, 9, 8, 7, 6, 5, 4]
    p = PrintTreeLayer()
    root = p.arrayToTree(array, 0)
    print(test.printFromTopToBottom(root))