gpt4 book ai didi

java - 如何实现二叉树

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:51 25 4
gpt4 key购买 nike

     package tree;

public class Tree {

TreeNode treenode=new TreeNode();
TreeNode root=null;

void insert(int data){
root=insert(root,data);

}

TreeNode insert(TreeNode node,int data)
{
if(node==null)
{
node=new TreeNode(data);
//node.data=data;

}
else
{

// while(node!=null){
if(node.lchild==null){
node.lchild=insert(node.lchild,data);
//node.lchild=node;
}
else if(node.rchild==null){

node.rchild=insert(node.rchild,data);
//node.lchild=node;
}

// }

}
return node;



}
void printTree(TreeNode treenode)
{
if(treenode==null){
return;
}
else
{
printTree(treenode.lchild);
System.out.print("->"+treenode.data);
printTree(treenode.rchild);

}
}

public void printTree() {
// TODO Auto-generated method stub
printTree(root);

}

void printTreePostOrder(TreeNode treenode)
{
System.out.println("Post Order");
if(treenode==null){
return;
}
else
{
printTree(treenode.lchild);
printTree(treenode.rchild);
System.out.print("->"+treenode.data);

}
}

public void printTreePostOrder() {
// TODO Auto-generated method stub
printTreePostOrder(root);

}



}

----------------2nd Class--------------------


package tree;

public class TreeNode {


enter code here
int data;
TreeNode lchild;
TreeNode rchild;



public TreeNode(int data) {
// TODO Auto-generated constructor stub
this.data=data;
this.rchild=null;
this.lchild=null;
}



public TreeNode() {
// TODO Auto-generated constructor stub
this.data=0;;
this.lchild=null;
this.rchild=null;
}



int getData()
{
return this.data;
}



public TreeNode getLchild() {
return lchild;
}



public void setLchild(TreeNode lchild) {
this.lchild = lchild;
}



public TreeNode getRchild() {
return rchild;
}



public void setRchild(TreeNode rchild) {
this.rchild = rchild;
}



public void setData(int data) {
this.data = data;
}


public static void main(String args[]){
Tree tree=new Tree();
tree.insert(4);
tree.insert(5);
tree.insert(2);
tree.insert(7);
tree.insert(1);
tree.insert(6);
tree.printTree();
tree.printTreePostOrder();

}

}

在此,我无法正确添加超过 3 个节点。 。我正在研究一个简单的有序二叉树,而不是二叉搜索树。谁能告诉这应该如何完成。我正在尝试实现二叉树而不是二叉搜索树

最佳答案

问题出在 insert(TreeNode node,int data) 方法的这一部分:

        if(node.lchild==null){
node.lchild=insert(node.lchild,data);
//node.lchild=node;
}
else if(node.rchild==null){

node.rchild=insert(node.rchild,data);
//node.lchild=node;
}

lchildrchild都不为空时,您没有处理这种情况。如果发生这种情况,您可以通过调用 insert(node.lchild,data)insert(node.rchild,data) 来递归调用这两个子级之一。

        if(node.lchild==null){
node.lchild=insert(node.lchild,data);
//node.lchild=node;
}
else if(node.rchild==null){

node.rchild=insert(node.rchild,data);
//node.lchild=node;
}else{
double random = Math.random();
if(random < 0.5)
insert(node.lchild, data);
else
insert(node.rchild, data);
}

关于java - 如何实现二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com