练习
定义
- 每个节点中的值必须大于(或等于)存储在其左侧子树中的任何值。
- 每个节点中的值必须小于(或等于)存储在其右子树中的任何值。
模板
function BST(root, target) {if (root.val == target)// 找到目标,做点什么if (root.val < target)BST(root.right, target);if (root.val > target)BST(root.left, target);}
应用
验证二叉搜索树
var isValidBST = function(root) {var helper = function(root, max, min){if(root == null) return true;if(max !== null && root.val >= max.val) return false;if(min !== null && root.val <= min.val) return false;return helper(root.left, root,min) && helper(root.right, max, root);};return helper(root,null,null);};
insert-into-a-binary-search-tree
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
var insertIntoBST = function(root, val) {if(root == null) {return new TreeNode(val)} else if (root.val > val) {root.left = insertIntoBST(root.left,val);} else {root.right = insertIntoBST(root.right, val);}return root;};
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
// 注意一下,这个删除操作并不完美,因为我们一般不会通过 root.val = minNode.val 修改节点内部的值来交换节点,// 而是通过一系列略微复杂的链表操作交换 root 和 minNode 两个节点。因为具体应用中,val 域可能会很大,// 修改起来很耗时,而链表操作无非改一改指针,而不会去碰内部数据。var deleteNode = function(root, key) {if(root == null) return root;if (root.val == key){// 找到目标,做点什么if(root.left == null) return root.right;if(root.right == null ) return root.left;// 处理情况 3let minNode = getMin(root.right);root.val = minNode.val;root.right = deleteNode(root.right, minNode.val);}if (root.val > key)root.left = deleteNode(root.left, key);if (root.val < key)root.right = deleteNode(root.right, key);return root;};var getMin = function (node) {// BST 最左边的就是最小的while (node.left != null) node = node.left;return node;}
