做网站15年,多少钱一度电,网站建设运营怎么办,WordPress 古腾堡开发【二叉搜索树定义】#xff08;BST#xff09;
二叉搜索树#xff08;Binary Search Tree#xff0c;简称 BST#xff09;是一种很常用的的二叉树。它的定义是#xff1a;一个二叉树中#xff0c;任意节点的值要大于等于左子树所有节点的值#xff0c;且要小于等于右边…【二叉搜索树定义】BST
二叉搜索树Binary Search Tree简称 BST是一种很常用的的二叉树。它的定义是一个二叉树中任意节点的值要大于等于左子树所有节点的值且要小于等于右边子树的所有节点的值。
【二叉树算法框架】
void traverse(TreeNode root) {// root 需要做什么在这做。// 其他的不用 root 操心抛给框架traverse(root.left);traverse(root.right);
}【二叉搜索树算法框架】
void BST(TreeNode root, int target) {if (root.val target)// 找到目标做点什么if (root.val target) BST(root.right, target);if (root.val target)BST(root.left, target);
}
【问题描述】
实现 BST 的基础操作判断 BST 的合法性、增、删、查。
【解答思路】 1. 判断 BST 的合法性
root 需要做的不只是和左右子节点比较而是要整个左子树和右子树所有节点比较。
boolean isValidBST(TreeNode root) {return isValidBST(root, null, null);
}boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {if (root null) return true;if (min ! null root.val min.val) return false;if (max ! null root.val max.val) return false;return isValidBST(root.left, min, root) isValidBST(root.right, root, max);
}
2. 在 BST 中查找一个数是否存在
框架
boolean isInBST(TreeNode root, int target) {if (root null) return false;if (root.val target) return true;return isInBST(root.left, target)|| isInBST(root.right, target);
}利用特性
boolean isInBST(TreeNode root, int target) {if (root null) return false;if (root.val target)return true;if (root.val target) return isInBST(root.right, target);if (root.val target)return isInBST(root.left, target);// root 该做的事做完了顺带把框架也完成了妙
}
3. 在 BST 中插入一个数
对数据结构的操作无非遍历 访问遍历就是“找”访问就是“改”。具体到这个问题插入一个数就是先找到插入位置然后进行插入操作。 直接套BST 中的遍历框架加上“改”的操作即可。一旦涉及“改”函数就要返回 TreeNode 类型并且对递归调用的返回值进行接收。
void BST(TreeNode root, int target) {if (root.val target)// 找到目标做点什么if (root.val target) BST(root.right, target);if (root.val target)BST(root.left, target);
}
4. 在 BST 中删除一个数 TreeNode deleteNode(TreeNode root, int key) {if (root null) return null;if (root.val key) {// 这两个 if 把情况 1 和 2 都正确处理了if (root.left null) return root.right;if (root.right null) return root.left;// 处理情况 3TreeNode minNode getMin(root.right);root.val minNode.val;root.right deleteNode(root.right, minNode.val);} else if (root.val key) {root.left deleteNode(root.left, key);} else if (root.val key) {root.right deleteNode(root.right, key);}return root;
}TreeNode getMin(TreeNode node) {// BST 最左边的就是最小的while (node.left ! null) node node.left;return node;
}
注意一下这个删除操作并不完美因为我们一般不会通过 root.val minNode.val 修改节点内部的值来交换节点而是通过一系列略微复杂的链表操作交换 root 和 minNode 两个节点。因为具体应用中val 域可能会很大修改起来很耗时而链表操作无非改一改指针而不会去碰内部数据。
【总结】
1. 二叉树算法设计的总路线把当前节点要做的事做好其他的交给递归框架不用当前节点操心。
2.如果当前节点会对下面的子节点有整体影响可以通过辅助函数增长参数列表借助参数传递信息。
3.在二叉树框架之上扩展出一套 BST 遍历框架
void BST(TreeNode root, int target) {if (root.val target)// 找到目标做点什么if (root.val target) BST(root.right, target);if (root.val target)BST(root.left, target);
}
转载链接https://leetcode-cn.com/problems/same-tree/solution/xie-shu-suan-fa-de-tao-lu-kuang-jia-by-wei-lai-bu-/