二叉树的测试代码
来源:7-5 定义递归问题 Binary Tree Path
慕勒9548534
2019-09-03
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;
}
}
写回答
1回答
-
liuyubobobo
2019-09-03
如果我要没理解错的话,你说的完全是 Leetcode上的297号问题:https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
我的思路可以参考这里(C++):
继续加油!:)
032019-09-03
相似问题