数据结构之二叉树查询
二叉树之查询
二叉树的查询是建立遍历的基础上更进一步的对比查询,下面分别从前序、中序、后续三种方法中查询对应的节点。
前序查找
/*** 前序查询*/public Person preSelectById(Integer id) {Person person = null;if (this.data.getId().equals(id)) {person = this.data;}if (Objects.isNull(person) && Objects.nonNull(this.left)) {person = this.left.preSelectById(id);}if (Objects.isNull(person) && Objects.nonNull(this.right)) {person = this.right.preSelectById(id);}return person;}
中序查找
/*** 中序查询*/public Person midSelectById(Integer id) {Person person = null;if (Objects.isNull(person) && Objects.nonNull(this.left)) {person = this.left.preSelectById(id);}if (this.data.getId().equals(id)) {person = this.data;}if (Objects.isNull(person) && Objects.nonNull(this.right)) {person = this.right.preSelectById(id);}return person;}
后序查找
/*** 后序查询*/public Person postSelectById(Integer id) {Person person = null;if (Objects.isNull(person) && Objects.nonNull(this.left)) {person = this.left.preSelectById(id);}if (Objects.isNull(person) && Objects.nonNull(this.right)) {person = this.right.preSelectById(id);}if (this.data.getId().equals(id)) {person = this.data;}return person;}
源码与测试案例
gitee地址