java - 建设树
问题描述
我写了一个树的构造方法。运行它时我没有看到任何错误。但是,当我测试树是否对称并且应该返回 false 时(对于输入:[1,2,2,4,4, null, 6])这意味着我将根节点设置为 1,第二级:2,2 第三级:4、4、null、6。它返回true。我不确定有什么问题?我确定我的对称函数是正确的,我只是不知道我的树结构有什么问题?我尝试调试,我看到数组中的所有值都在构造中实现。有人可以让我知道发生了什么吗?
public class isSymmetric {
public static class TreeNode {
public int key;
public TreeNode left;
public TreeNode right;
public TreeNode(int key) {
this.key = key;
this.left = this.right = null;
}
}
public boolean symmetric(TreeNode root) {
...
}
//Tree test cases
public static TreeNode construction(Integer[] array) {
//use level order traversal to construct a tree
TreeNode root = new TreeNode(array[0]);
return constructionhelp(array, root, 0);
}
public static TreeNode constructionhelp(Integer[] array, TreeNode root, int i) {
if (root == null) {
return null;
}
if (i < array.length) {
root = new TreeNode(array[i]);
root.left = constructionhelp(array, root.left, 2*i+1);
root.right = constructionhelp(array, root.right, 2*i+2);
}
return root;
}
public static void main(String[] args) {
isSymmetric s = new isSymmetric();
Integer a[] = {1,2,2,4,4,null,6};
TreeNode roota = construction(a);
System.out.print(s.symmetric(roota));
}
}
//returning true;
解决方案
怎么了:
root = new TreeNode(array[i]); // you create new tree node instance
root.left = constructionhelp(array, root.left, 2*i+1); // root.left is null
root.right = constructionhelp(array, root.right, 2*i+2) // root.right is null
所以在你constructionhelp
再次调用你之后,你null
作为节点的参数传递。
->null
返回。
-> 你的树只是根。
推荐阅读
- javascript - mTLS 验证和 ngrok
- javascript - 无法覆盖 Ant Design 垂直子菜单背景颜色
- python - SimpleITK 无法显示图像
- python - model.train_on_batch() 实际上在做什么?
- javascript - 我有几个编辑器和几个终端。我可以将它们配对为终端 ID 与编辑器中的文件吗?
- c# - 如何使用 C# ClientWebSocket 设置自定义 Sec-WebSocket-Protocol?
- python - 是否有在 VS 代码上运行代码的选项
- ios - 更新旧的 Xcode 项目,但现在导航栏背景延伸到导航栏的高度以下
- flutter - Flutter 转换 - UICollectionViewDiffableDataSource
- python - Python计算两个文件目录的余弦相似度