We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接: 938. 二叉搜索树的范围和
解题思路:
[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 }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:
938. 二叉搜索树的范围和
解题思路:
[low, high]
之间,就进行加和。The text was updated successfully, but these errors were encountered: