[菜鸟刷题]算法——二叉搜索树Ⅱ

179 阅读1分钟

98. 验证二叉搜索树

image.png

【题解】

通过使用辅助函数,增加函数参数列表,在参数中携带额外信息,将这种约束传递给子树的所有节点,限定以 root 为根的子树节点必须满足 max.val > root.val > min.val

【代码】

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
 var isValidBST = function(root) {
  return _isValidBST(root, null, null)
};
function _isValidBST(root, min, max) {
  if (root === null) {
    return true
  }
  // 若 root.val 不符合 max 和 min 的限制,说明不是合法 BST
  if(max !== null && root.val >= max.val) return false
  if(min !== null && root.val <= min.val) return false

  return _isValidBST(root.left, min, root) && _isValidBST(root.right, root, max)
}

230. 二叉搜索树中第K小的元素

image.png

【题解】

  • 我们想找到第k小的数字,根据二叉搜索树的性质,如果将所有节点的数字从小到大放入到一个数组中ret中,答案即为ret[k-1]
  • 递归实现,根据二叉搜索树的性质,中序遍历二叉搜索树,即先查找左子树,然后将当前节点放入数组ret中,然后先查找右子树,不断重复上述过程,直至遍历到叶子节点结束

【代码】

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */

 var kthSmallest = function(root, k) {
  let ret = []
  function dfs(root) {
    if (root !== null && root.left !== null) {
      dfs(root.left)
    }
    ret.push(root.val)
    if (root !== null && root.right !== null) {
      dfs(root.right)
    }
  }
  dfs(root)
  return ret[k-1]
};