Skip to content

LeetCode题解:938. 二叉搜索树的范围和,栈,JavaScript,详细注释 #393

Description

@chencl1986

原题链接:
938. 二叉搜索树的范围和

解题思路:

  1. 使用中序遍历,即可按顺序获取到二叉搜索树的每个节点。
  2. 当节点的值在[low, high]之间,就进行加和。
/**
 * @param {TreeNode} root
 * @param {number} low
 * @param {number} high
 * @return {number}
 */
var rangeSumBST = function (root, low, high) {
  let sum = 0 // 缓存结点值之和
  let stack = [] // 使用栈辅助遍历
  let current = root // 使用节点进行遍历

  // 中序遍历二叉树
  // 遍历的过程中,可能出现current为空,而stack中有元素,即为遍历到树的最底端。
  // 也可能出现current有值而stack为空的情况,如遍历到二叉树的根节点。
  while (stack.length || current) {
    // 不断向左下遍历节点,同时将所有节点入栈
    // 这样就保证了总是从最左端开始遍历节点
    while (current) {
      stack.push(current)
      current = current.left
    }

    // 从栈中弹出节点,即为当前遍历的节点
    // 弹出节点的顺序为从左到右。
    const node = stack.pop()

    // 处理中序遍历读取到的节点
    // 节点的值在[low, high]之间,就进行加和
    if (node.val >= low && node.val <= high) {
      sum += node.val
    }

    // 不断向右侧遍历树,如果右侧节点为空,则会从栈中弹出当前子树的根节点
    // 这样就形成了从左到右的遍历顺序
    current = node.right
  }

  return sum
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions