從上到下打印二叉樹題解

題目:

從上到下打印出二叉樹的每個節點,同一層的節點按照從左到右的順序打印。

 

例如:
給定二叉樹: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回:

[3,9,20,15,7]
 

提示:

節點總數 <= 1000

思路:

層次遍歷二叉樹

代碼:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;

class Solution {
    public int[] levelOrder(TreeNode root) {
        if(root == null) {
            return new int[0];
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> vals = new ArrayList<>();
        queue.offer(root);
        TreeNode cur = null;
        while(!queue.isEmpty()) {
            cur = queue.poll();
            vals.add(cur.val);
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
        
        return vals.stream().mapToInt(Integer::valueOf).toArray();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章