栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

二叉树的构建代码(普通写法+递归写法)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的构建代码(普通写法+递归写法)

二叉树的构建 首先创建三个类
//TreeNode构建每一个树节点,包括树的左子树、右子树和值(value)
public class TreeNode {
  public TreeNode leftChild;
  public TreeNode rightChild;
  public Integer value;
  public TreeNode(Integer value) {
	  this.value=value;
  }
}
//用于构建树的算法
public class BinaryTree{
    //定义根
	TreeNode root;
    //普通插入树节点的方法
	public void insert(Integer value) {
		TreeNode node=new TreeNode(value);
		if(root==null) {
			root=node;
			return;
		}		
		TreeNode parent;
		TreeNode temp=root;
		while(true) {
			parent=root;
			if(node.value>temp.value) {
				temp=temp.rightChild;
				if(temp==null) {
					parent.rightChild=node;
					return;
				}
			}else {
				temp=temp.leftChild;
				if(temp==null) {
					parent.leftChild=node;
					return;
				}
			}

		}
	} 
    //递归方法
	public TreeNode insertD(Integer value,TreeNode Dnode) {
		TreeNode node=new TreeNode(value);
		if(root==null) {
			root=node;
			return root;
		}
		while(true) {
			if(value>Dnode.value) {
				if(Dnode.rightChild==null) {
					Dnode.rightChild=node;
					return root;
				}
				return insertD(value,Dnode.rightChild);
			}else {
				if(Dnode.leftChild==null) {
					Dnode.leftChild=node;
					return root;
				}
				return insertD(value,Dnode.leftChild);
			}
		}
	}
	
}



public class TestTree {
public static void main(String[] args) {
	BinaryTree t1=new BinaryTree();
	t1.insert(5,t1.root);
	t1.insertD(5,t1.root);
	t1.insertD(2,t1.root);

}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/692030.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号