对于任何一个非叶子结点,它的左子节点均为它小,它的右子结点均比它大
private static class TreeNode{
?
int val;
TreeNode left;
TreeNode right;
?
public TreeNode(int val) {
this.val = val;
}
?
}
public static class BSTree{
?
// 根结点
private TreeNode root;
?
}
// 结点中方法:根据二叉排序树的规则添加结点 public void add(TreeNode newNode){ ? if (newNode == null){ return ; } ? /** * 如果当前新结点的值大于当前结点this * 如果当前结点右子树为空,直接添加 * 否则,右子树重新调用add方法,重复此步骤 */ if (newNode.val >= this.val){ if (this.right == null){ this.right = newNode; }else { this.right.add(newNode); } }else { if (this.left == null){ this.left = newNode; }else { this.left.add(newNode); } } } ? // 树中方法 public void add(TreeNode node){ ? if(root == null){ root = node; }else { root.add(node); } } ? // 构建二叉搜索树方法 public static BSTree constructBST(int[] array){ ? if (array.length == 0){ return null; } ? // 创建二叉排序树 BSTree tree = new BSTree(); ? for (int i = 0; i < array.length; i++) { tree.add(new TreeNode(array[i])); } ? return tree; ? }
// 结点中方法:查找结点,该结点值为val public TreeNode findNode(int nodeVal){ ? if (this.val == nodeVal){ return this; }else if (nodeVal < this.val){ if (this.left == null){ return null; }else { return this.left.findNode(nodeVal); } }else { if (this.right == null){ return null; }else { return this.right.findNode(nodeVal); } } } ? // 树中方法 public TreeNode find(TreeNode node){ ? if (node == null){ return null; }else { return root.findNode(node.val); } }
// 结点中方法:查找要删除结点的父节点 public TreeNode findFatherNode(int nodeVal){ ? // 如果当前结点为父节点 if((this.left != null && this.left.val == nodeVal) || (this.right != null && this.right.val == nodeVal)){ return this; } // 如果左子树不为空,并且nodeVal小于当前结点的值 else if(this.left != null && nodeVal < this.left.val){ return this.left.findFatherNode(nodeVal); } // 如果右子树不为空,并且nodeVal大于等于当前结点的值 else if (this.right != null && nodeVal >= this.right.val){ return this.right.findFatherNode(nodeVal); } else { return null; } ? } ? // 树中方法 public TreeNode findParent(TreeNode node){ ? if (node == null){ return null; }else { return root.findFatherNode(node.val); } }
原文:https://www.cnblogs.com/LittleSkinny/p/14419413.html