二叉树

还有很多不友好的地方,关于delete方法,涉及到把原来的对象改得乱七八糟,只好最后返回一个新的对象

 

find();

insert();

delete();

preOrder(); inOrder(); postOrder(); 

getSuccessor();

creatTree();

 

public class Tree {

	private Node root;

	public Tree(Node root) {
		this.root = root;
	}

	public Node getRoot() {
		return root;
	}

	public Node find(int key) {
		Node current = root;
		if (current == null) {
			return null;
		}
		while (current.getKey() != key) {
			if (current.getKey() > key) {
				current = current.getLeftChild();
			} else {
				current = current.getRightChild();
			}
			if (current == null) {
				return null;// not find
			}
		}// find it
		return current;
	}

	public boolean insert2(Node node) {
		Node current = root;
		if (current == null) {
			return false;
		}
		int key = node.getKey();
		while (current.getKey() != key) {
			Node parent = current;
			if (current.getKey() > key) {
				current = current.getLeftChild();
			} else {
				current = current.getRightChild();
			}
			if (current == null) {
				if (parent.getKey() > key) {
					parent.setLeftChild(node);
				} else {
					parent.setRightChild(node);
				}
				return true;
			}
		}

		return false;
	}

	public void insert(Node node) {
		if (root == null) {
			root = node;
			return;
		}
		Node current = root;
		while (current.getLeftChild() != null
				&& current.getRightChild() != null) {
			if (current.getKey() >= node.getKey()) {
				current = current.getLeftChild();
			} else {
				current = current.getRightChild();
			}
		}
		while (current.getLeftChild() != null) {
			if (current.getKey() >= node.getKey())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树是一种常见的数据结构,由节点和边组成。每个节点最多有两个子节点,分别称为左子节点和右子节点。 创建二叉树的方法有多种。一种常用的方法是使用链式存储结构,即每个节点含有数据和指向左右子节点的指针。我们可以通过递归的方式创建二叉树。 首先,我们需要定义一个二叉树节点的结构,包括数据和左右子节点的指针。然后,按照二叉树的性质,递归地创建节点。具体步骤如下: 1. 创建一个根节点,将根节点的数据填入。 2. 如果输入数据为空,表示当前节点为叶子节点,返回。 3. 从输入数据中取出左子节点的数据。 4. 创建左子节点,并将其指针赋值给根节点的左子节点指针。 5. 递归地调用创建二叉树的函数,将左子节点作为参数。 6. 从输入数据中取出右子节点的数据。 7. 创建右子节点,并将其指针赋值给根节点的右子节点指针。 8. 递归地调用创建二叉树的函数,将右子节点作为参数。 当所有节点都创建完成后,我们就得到了一颗二叉树。可以根据需要对二叉树进行遍历、插入、删除等操作。 需要注意的是,在创建二叉树时,输入数据需要按照特定的规则进行排序,以满足二叉树的性质。例如,如果输入数据是升序排列的,则创建出的二叉树将是一个平衡二叉搜索树。 所以,创建二叉树的过程就是递归地将输入数据分配到每个节点,并按照二叉树的性质建立节点之间的连接关系。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值