数据结构Java版之二叉查找树(七)
二叉查找树(BST : BInary Search Tree)
二叉查找树的性质:
1.每一个元素有一个键值
2.左子树的键值都小于根节点的键值
3.右子树的键值都大于根节点的键值
4.左右子树都是二叉查找树
二叉查找树查找一个数据的速度非常快,在庞大的数据中,左右来回较少的次数就能找到。下面来做一个二叉查找树。
1.创建一个节点类:
// 树节点 class TreeNode { public char val; public TreeNode left; public TreeNode right; public TreeNode(char x) { val = x; } }
2.完整代码:
package tree; public class BinaryFindTree { private TreeNode root; public BinaryFindTree(TreeNode root) { this.root = root; } //插入节点 public boolean Insert(TreeNode x) { TreeNode p = root; TreeNode q = null; //查找插入的位置 while(p != null) { q = p; if(x.val == p.val) {return false;} if(x.val < p.val) {p = p.left;} else {p = p.right;} } //找到的位置就是q if(root == null) root = x; else if (x.val < q.val) q.left = x; else q.right = x; return true; } //递归查找 public TreeNode Search(TreeNode x) { return Search(root, x); } public TreeNode Search(TreeNode b, TreeNode x) { if(b == null) return null; if(x.val == b.val) return b; if(x.val < b.val) return Search(b.left, x); return Search(b.right, x); } //迭代查找 public TreeNode IterSearch(TreeNode x) { TreeNode t = root; while(t != null) { if(t.val == x.val) return t; if(x.val < t.val) t = t.left; else t = t.right; } return null; } // 树节点 class TreeNode { public char val; public TreeNode left; public TreeNode right; public TreeNode(char x) { val = x; } } }