JavaScript刷LeetCode -- 98. Validate Binary Search Tree
阿新 • • 發佈:2018-12-29
一、題目
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and right subtrees must also be binary search trees.
二、題目大意
驗證一棵二叉樹是否為二叉搜尋樹。
三、解題思路
遞迴遍歷出該二叉樹的中序遍歷陣列,判斷該陣列是否為單調遞增陣列。
四、程式碼實現
const isValidBST = root => { const ans = [] help(root) for (let i = 0, max = ans.length; i < max - 1; i++) { const pre = ans[i] const next = ans[i + 1] if (next <= pre) { return false } } return true function help (root) { if (!root) { return } help(root.left) ans.push(root.val) help(root.right) } }
如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。