Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left 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.
Example 1:

Input: root = [2,1,3] Output: true
Example 2:

Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4.
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. -231 <= Node.val <= 231 - 1
A:
-------利用传入的参数,每次返回其子树的范围--------再对比-------------
------------------------不同于每次返回其子树的范围, 我们给出其范围。----但是这样, 如果val 是double就会有问题-------------------
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/class Solution {public:bool isValidBST(TreeNode* root) { return helper(LONG_MIN, root, LONG_MAX); }private:bool helper(long lower, TreeNode* root, long upper) {if (!root)return true;long val = root->val;return val > lower && val < upper && helper(lower, root->left, val) &&helper(val, root->right, upper);}};
-----------------------------把树弄成一个list, 然后对比。---------------------
public class Solution { public boolean isValidBST(TreeNode root) { if(root == null){ return true; } // in-order traversal, to compare Stack<Integer> stack = new Stack<Integer>(); inOrderTraversal(root,stack); //stack is not empty, since root is not null int lastPop = stack.pop(); while(!stack.isEmpty()){ int curPop = stack.pop(); if(curPop >= lastPop){ return false; } lastPop = curPop; } return true; } private void inOrderTraversal(TreeNode root, Stack<Integer> stack){ if(root == null){ return; } inOrderTraversal(root.left,stack); stack.push(root.val); inOrderTraversal(root.right,stack); } }
Mistakes:
1:刚开始,没注意,是strictly less than, (more than)
哎,第二遍,又是犯了这个错误。
2: 这道题目的关键点就是 root.val可能是极值。因此要跟Long 的值对比。
No comments:
Post a Comment