二叉树的测试代码

来源: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++):

https://github.com/liuyubobobo/Play-Leetcode/tree/master/0297-Serialize-and-Deserialize-Binary-Tree/cpp-0297 


继续加油!:)

0
3
慕勒9548534
回复
liuyubobobo
我明白了,谢谢老师
2019-09-03
共3条回复

玩转算法面试-- Leetcode真题分门别类讲解

课程配套大量BAT面试真题,高频算法题解析,强化训练

7410 学习 · 1150 问题

查看课程