add: 验证二叉搜索树

This commit is contained in:
2020-05-05 18:25:52 +08:00
parent b806ec7959
commit aa83ce62e9
6 changed files with 82 additions and 42 deletions

40
test/tree/Tree.js Normal file
View File

@ -0,0 +1,40 @@
import TreeNode from './TreeNode'
export default class Tree {
constructor () {
this.root = null
this.queue = []
this.insertNum = 0
}
insert (val) {
this.insertNum++ // 插入次数加1
const node = (!val && typeof val === 'object') ? null : new TreeNode(val) // 判断是否为空节点
if (!this.root) { // 判断根节点是否存在
this.root = node // 插入根节点
node && this.queue.push(this.root) // 非空节点入列
} else { // 插入非根节点
const parent = this.queue[0] // 被插入的父节点
if (!(this.insertNum % 2)) { // 通过插入次数判断左右
parent.left = node // 插入左边
node && this.queue.push(parent.left) // 非空节点入列
} else {
parent.right = node // 插入右边
node && this.queue.push(parent.right) // 非空节点入列
this.queue.shift() // 当前父节点parent 已经不可能再插入子节点,故出列
}
}
return this
}
static arrToTree (arr) {
const tree = new Tree()
for (const n in arr) {
tree.insert(arr[n])
}
return tree.root
}
}

7
test/tree/TreeNode.js Normal file
View File

@ -0,0 +1,7 @@
export default class TreeNode {
constructor (val) {
this.val = val
this.left = null
this.right = null
}
}

View File

@ -1,48 +1,8 @@
import { rightSideView } from '../../src/tree/binary-tree-right-side-view'
import Tree from './Tree'
test('二叉树的右视图', () => {
function TreeNode (val) {
this.val = val
this.left = null
this.right = null
}
class Tree {
constructor () {
this.root = null
this.queue = []
this.insertNum = 0
}
insert (val) {
this.insertNum++ // 插入次数加1
const node = (!val && typeof val === 'object') ? null : new TreeNode(val) // 判断是否为空节点
if (!this.root) { // 判断根节点是否存在
this.root = node // 插入根节点
node && this.queue.push(this.root) // 非空节点入列
} else { // 插入非根节点
const parent = this.queue[0] // 被插入的父节点
if (!(this.insertNum % 2)) { // 通过插入次数判断左右
parent.left = node // 插入左边
node && this.queue.push(parent.left) // 非空节点入列
} else {
parent.right = node // 插入右边
node && this.queue.push(parent.right) // 非空节点入列
this.queue.shift() // 当前父节点parent 已经不可能再插入子节点,故出列
}
}
return this
}
}
const arr = [1, 2, 3, null, 5, null, 4]
const tree = new Tree()
for (const n in arr) {
tree.insert(arr[n])
}
expect(rightSideView(tree.root)).toEqual([1, 3, 4])
expect(rightSideView(Tree.arrToTree(arr))).toEqual([1, 3, 4])
})

View File

@ -0,0 +1,12 @@
import { isValidBST } from '../../src/tree/validate-binary-search-tree'
import Tree from './Tree'
test('验证二叉搜索树', () => {
expect(isValidBST(Tree.arrToTree([1, 1]))).toBe(false)
expect(isValidBST(Tree.arrToTree([2, 1, 3]))).toBe(true)
expect(isValidBST(Tree.arrToTree([5, 1, 4, null, null, 3, 6]))).toBe(false)
expect(isValidBST(Tree.arrToTree([-1]))).toBe(true)
expect(isValidBST(Tree.arrToTree([2, 1, 4, null, null, 3, 5]))).toBe(true)
expect(isValidBST(null)).toBe(true)
expect(isValidBST(Tree.arrToTree([10, 5, 15, null, null, 6, 20]))).toBe(false)
})