Java 方法二叉树
我不得不做一些关于BinaryTree(无搜索二叉树)的方法。我无法使用3种方法:反射(反射树,我的代码不工作,因为只反射树的一部分)、剪切和剪切2。代码是:Java 方法二叉树,java,binary-tree,Java,Binary Tree,我不得不做一些关于BinaryTree(无搜索二叉树)的方法。我无法使用3种方法:反射(反射树,我的代码不工作,因为只反射树的一部分)、剪切和剪切2。代码是: public class BinaryTree { protected class Node { Integer element; Node left; Node right; Node(int element) { this.eleme
public class BinaryTree {
protected class Node {
Integer element;
Node left;
Node right;
Node(int element) {
this.element = element;
left = right = null;
}
Node(int element, Node left, Node right) {
this.element = element;
this.left = left;
this.right = right;
}
// is leaf?
boolean isLeaf() {
return left == null && right == null;
}
}
protected Node root;
public BinaryTree() {
root = null;
}
/* doesn't work */
public void reflect() {
if (root == null)
return;
reflect(root);
}
protected void reflect(Node node) {
reflect(node.left);
reflect(node.right);
Node temp = new Node(node.left.element);
node.left.element = node.right.element;
node.right.element = temp.element;
}
/* this method had to trim the tree at level h,
if h=0, it cut the whole tree. It change the original tree */
/* doesn't work */
public void cut(int h) {
}
/* i can change parameters */
protected void cut(Node node, int h) {
}
/* this method had to trim the tree at level h,
if h=0, it cut the whole tree. It doesn't change the original tree,
it returns a new tree */
/* doesn't work */
public BinaryTree cut2(int h) {
}
/* i can change parameters */
protected BinaryTree cut2(Node node, int h) {
}
}
}
我不能做的方法反映削减和削减2。请帮帮我,谢谢 你几乎对了
reflect
。只需避免创建新的节点对象:
protected void reflect(Node node) {
if (node != null) {
reflect(node.left);
reflect(node.right);
Node temp = node.left;
node.left = node.right;
node.right = temp;
}
}
对于切割
:
public void cut(int h) {
if (h == 0) {
root = null;
} else {
cut(root, h - 1);
}
}
然后您可以编写cut(Node,int)
:
看看你能不能从上面的开始自己计算出
cut2
。这听起来像是家庭作业,即使标签被删掉了,我认为我们编写完整的二叉树实现是不对的
话虽如此,您能否解释一下实现这两种方法有什么不清楚的地方?除了
cut2
所需的树复制之外,它们几乎相等。我将通过递归私有方法cutInternal(Node n,int currLevel,int h)
传递我们当前所在的级别号来实现它。然后,当currLevel==h时,我们只需修剪两个节点并返回。具体问题是什么?Stackoverflow用户不会编写您的代码。@user1786048-有什么问题吗?如果它抛出一个NullPointerException,那么您需要防止null
节点。我已经更新了我的代码(对于reflect
和cut
),以执行null
检查。如果是别的,请详细说明.public void cut(int h){If(root==null)System.out.println(“Albero vooto!”);else If(h<0)System.out.println(“Livello non valido!”);else cut(root,h,0);}受保护的void cut(Node Node,int h,int liv){If(h>=liv)Node.left=Node.right=null;else{If(node.right!=null)cut(node.right,h,liv+1);if(node.left!=null)cut(node.left,h,liv+1);}我已经写了这些方法,但不起作用..我不明白为什么。。
protected void cut(Node node, int h) {
if (node != null) {
if (h == 0) {
node.left = node.right = null;
} else {
cut(node.left, h - 1);
cut(node.right, h - 1);
}
}
}