编程题
树
94. 二叉树的中序遍历
var inorderTraversal = function(root) {
return Array.from(fn(root))
};
function* fn(root) {
if (root) {
yield* fn(root.left)
yield root.val
yield* fn(root.right)
}
}
98. 验证二叉搜索树
var isValidBST = function(root) {
return helper(root)
};
function helper(root, min = -Infinity, max = Infinity) {
if (!root) return true;
const { val, left, right } = root
if (val <= min || val >= max) return false;
return helper(left, min, val) && helper(right, val, max);
}
var isValidBST = function(root) {
try {
helper(root)
return true;
} catch {
return false;
}
}
function helper(root, result = []) {
if (root) {
helper(root.left, result);
if (result.length === 0 || root.val > result[result.length - 1]) {
result.push(root.val)
} else {
throw new Error('')
}
helper(root.right, result);
}
return result;
}