开发中常见的算法汇总之-二叉树查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cpongo4/article/details/89333901
#### 二叉树查找 - 核心思想 - 构建一棵已排序的二叉树满足:树中的每个节点的值均大于其左孩子节点的值,每个节点的值小于其有孩子节点的值,运用二分查找特性在树中进行查找 - 特性 - 基于二叉树的结构来存储源数据 - 基于二分查找特性 - 步骤 - 依据(父节点大于左孩子节点但小于右孩子节点)构建一棵二叉树 - 在树中查找目标值,目标值和根节点比较,小于根节点往根节点左侧往下找,大于根节点往根节点右侧往下找 - 图解 006tNc79gy1g23haymvm1g30sg0m0tg0.gif - 示例 ```java package com.lyd.algorithm.find; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * 描述:二叉树查找 *

* # *

* * @author lyd Date 2019/4/15 ProjectName:datastructure-algo Version: 1.0 */ @Slf4j public class BinaryTreeSearch { static int count = 0; /** * 树的根节点 */ private Node root; /** * 往树中添加节点数据 * @param value 值 */ public void insertion(int value) { if (null == root) { root = new Node(value); } else { adjNode(root, value); } } /** * 大于父节点的数据往右孩子节点方向插入 * 小于父节点的数据往左孩子节点方向插入 */ private void adjNode(Node node, int value) { if (null == node) { return; } Node left = node.left; Node right = node.right; int nodeV = node.value; if (value <= nodeV) { if (null != left) { adjNode(left, value); } else { node.left = new Node(value); } }else{ if (null != right) { adjNode(right, value); } else { node.right = new Node(value); } } } /** * 二分查找该树 * @param value 目标值 * @return true存在|false不存在 */ public boolean binaryTreeSearch(int value) { return null != search(root, value); } private Node search(Node node, int value) { if (null == node) { return null; } Node left = node.left; Node right = node.right; int nodeV = node.value; if (nodeV == value) { return node; } count++; if (value < nodeV && null != left) { return search(left, value); } if (value > nodeV && null != right) { return search(right, value); } return null; } /** * 树节点 */ @Data @AllArgsConstructor @NoArgsConstructor static class Node { private int value; private Node left; private Node right; public Node(int value) { this.value = value; } } public static void main(String[] args) { BinaryTreeSearch bts = new BinaryTreeSearch(); int[] source = new int[]{2, 2, 3, 13, 15, 13, 5, 6, 11, 16, 20, 17, 12, 5, 6, 11, 16, 11, 20, 17}; for (int i = 0; i < source.length; i++) { bts.insertion(source[i]); } int target = 5; boolean result = bts.binaryTreeSearch(target); log.info("call binaryTreeSearch count:{},result:{},target:{},source:{}", count, result, target, source); } } ```

猜你喜欢

转载自blog.csdn.net/cpongo4/article/details/89333901