按照前序遍历得到数组,然后看是否是有序的,时间优于 5%,空间优于 10%。
- var isValidBST = function(root) {
- if(root == null || (root.left == null && root.right == null)) return true;
-
- function flatTree(root) {
- if(root == null || root == undefined) return [];
- return [...flatTree(root.left), root.val, ...flatTree(root.right)];
- }
-
- let flatedList = flatTree(root);
-
- for(let i = 1; i< flatedList.length; i++) {
- if(flatedList[i] <= flatedList[i - 1]) return false;
- }
-
- return true;
- };