飞书日常实习面试
飞书日常实习面试
tcp的拥塞控制
mysql的设计模式 隔离模式
HashMap的实现
一亿个数字找最大的十个数
mysql的设计模式 隔离模式
HashMap的实现
一亿个数字找最大的十个数
算法题 (考察bfs)
给定一个二叉树,输出每一层的数据的和
1
2 3
4 5 6 7
输出 1 5 22
import java.util.*; class TreeNode{ TreeNode(int val){ this.val = val; } int val; TreeNode left; TreeNode right; } public class Main { public static void main(String[] args) { TreeNode root = new TreeNode(1); TreeNode root2 = new TreeNode(2); TreeNode root3 = new TreeNode(3); TreeNode root4 = new TreeNode(4); TreeNode root5 = new TreeNode(5); TreeNode root6 = new TreeNode(6); TreeNode root7 = new TreeNode(7); root.left = root2; root.right = root3; root2.left = root4; root2.right = root5; root3.left = root6; root3.right = root7; //输入根节点 root Queue<TreeNode> q = new LinkedList<>(); //储存每一层数据的和 ArrayList<Integer> list = new ArrayList<>(); q.offer(root); while(!q.isEmpty()){ int n = q.size(); int sum = 0; for(int i = 0;i < n;i++){ TreeNode node = q.poll(); sum += node.val; if(node.left != null){ q.offer(node.left); } if(node.right != null){ q.offer(node.right); } } list.add(sum); } //打印每一层的数据的和 for(Integer sum:list){ System.out.print(sum + " "); } } }