bobo老师好,之前就一直想写一个测试代码,便于本地编译器debug,正好今天笔试结果就需要自己写一个二叉树测试代码,结果写了个大概,请老师看一看我写的对不对,因为我一时半会没想出怎么打印输出验证生成的二叉树是否正确,麻烦老师了
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
public static TreeNode create(String[] arr) {
int n = arr.length;
TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int i = 1;
while(!q.isEmpty()) {
if(i >= n) break;
TreeNode cur = q.poll();
if(cur != null) {
if(i < n && arr[i] != null) {
cur.left = new TreeNode(Integer.parseInt(arr[i]));
i ++;
q.add(cur.left);
}else {
cur.left = null;
i ++;
q.add(cur.left);
}
if(i < n && arr[i] != null) {
cur.right = new TreeNode(Integer.parseInt(arr[i]));
i ++;
q.add(cur.right);
}else {
cur.right = null;
i ++;
q.add(cur.right);
}
}
}
return root;
}
}