LeetCode:Validate Binary Search Tree(iupdate)
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
中序遍历验证是否是..
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 //中序遍历就可以 12 private: 13 TreeNode *prenode; 14 public: 15 bool isValidBST(TreeNode* root) { 16 17 if(root) 18 { 19 if(!isValidBST(root->left)) return false; 20 if(prenode&&prenode->val>=root->val) 21 return false; 22 prenode=root; 23 24 if(!isValidBST(root->right)) return false; 25 } 26 return true; 27 28 } 29 30 31 };