part one parent()
public TreeNode parent() throws InvalidNodeException { // REPLACE THE FOLLOWING LINE WITH YOUR SOLUTION TO PART I. if(!this.valid){ throw new InvalidNodeException(); } if(this.parent==null) return new SibTreeNode(); return this.parent; }
part two insertChild()
public void insertChild(Object item, int c) throws InvalidNodeException { // FILL IN YOUR SOLUTION TO PART II HERE. if(!this.valid){throw new InvalidNodeException();} SibTreeNode Child = new SibTreeNode(this.myTree,item); Child.parent=this; this.myTree.size++; if(this.firstChild==null){ this.firstChild=Child; return; } if(c<1){c=1;} if(c==1){ Child.nextSibling=this.firstChild; this.firstChild=Child; }else{ int num=2; SibTreeNode CurrentNode=this.firstChild; while(num<c){ num++; if(CurrentNode.valid&&CurrentNode.nextSibling!=null){ CurrentNode=CurrentNode.nextSibling; } } Child.nextSibling=CurrentNode.nextSibling; CurrentNode.nextSibling=Child; } }
part three removeLeaf()
public void removeLeaf() throws InvalidNodeException { // FILL IN YOUR SOLUTION TO PART III HERE. if(!this.valid){throw new InvalidNodeException();} if(myTree.size==1){myTree.size--;this.myTree.root=null;this.valid=false;return;} if(this.firstChild==null&&this.myTree.size>1){ this.myTree.size--; if(this.myTree.size==1){this.valid=false;} SibTreeNode leafParent=this.parent; this.valid=false; SibTreeNode CurrentNode = leafParent.firstChild; if(!CurrentNode.valid){ leafParent.firstChild=CurrentNode.nextSibling; return; } while(true){ if(!CurrentNode.nextSibling.valid){ CurrentNode.nextSibling=CurrentNode.nextSibling.nextSibling; return; } CurrentNode=CurrentNode.nextSibling; } }
运行结果:
时间: 2024-12-19 18:34:01