当前位置:网站首页>Leecode brush questions record interview questions 32 - I. print binary tree from top to bottom

Leecode brush questions record interview questions 32 - I. print binary tree from top to bottom

2022-07-07 00:12:00 Why is there a bug list

List of articles

topic

Print out each node of the binary tree from top to bottom , Nodes of the same layer are printed from left to right .

for example :
Given binary tree : [3,9,20,null,null,15,7],

3

/
9 20
/
15 7
return :

[3,9,20,15,7]

Tips :

Total number of nodes <= 1000

answer

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
class Solution {
    
    public int[] levelOrder(TreeNode root)
        {
    
            if(root == null) 
             {
    
                int[] a = {
    };
                return a;
            }
           Queue<TreeNode> arrayBlockingQueue = new ArrayBlockingQueue<TreeNode>(1000);
            ArrayList<Integer> result = new ArrayList<>();
            arrayBlockingQueue.add(root);
            while (!arrayBlockingQueue.isEmpty())
            {
    
                TreeNode treeNode = arrayBlockingQueue.poll();
                result.add(treeNode.val);
                if(treeNode.left != null) arrayBlockingQueue.add(treeNode.left);
                if(treeNode.right != null) arrayBlockingQueue.add(treeNode.right);
            }
            int[] sz = new int[result.size()];
            for(int i = 0 ;i < result.size(); i ++)
            {
    
                sz[i] = result.get(i);
            }
            return sz;
        }
}
原网站

版权声明
本文为[Why is there a bug list]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131017365135.html