做实习笔试时遇到的一个题里用到了根据层序遍历的结果来构建二叉树。全部代码如下
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine();//输入节点数量 int len = Integer.parseInt(str); int[] nums = new int[len]; str = br.readLine();//输入节点内容 StringTokenizer st = new StringTokenizer(str); int i = 0; //将节点数值存入数组中 while(st.hasMoreTokens()){ nums[i++] = Integer.parseInt(st.nextToken()); } Queue<TreeNode> queue = new ArrayDeque<>(); TreeNode root= null;//根节点 int index = 0; while(index < len){ //如果队列中没有节点,创建根结点放入其中 if(queue.isEmpty()){ root = new TreeNode(nums[index++]); queue.add(root); }else { //如果有了节点,开始取节点,添加子节点 TreeNode node = queue.poll(); if (index < len){ node.left = new TreeNode(nums[index++]); queue.add(node.left); } if (index < len) { node.right = new TreeNode(nums[index++]); queue.add(node.right); } } } //先序遍历验证构建结果 pre(root); } private static void pre(TreeNode root){ if(root == null) return; System.out.println(root.val); pre(root.left); pre(root.right); } } class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int val){this.val = val;} }
标签:index,遍历,TreeNode,int,层序,二叉树,new,root,节点 From: https://www.cnblogs.com/myz99/p/17455341.html