[Leetcode] Validate binary search tree 验证二叉搜索树
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
二叉搜索树:若是所有结点互不相等,满足:在任一结点r的左(右)子树中,所有结点(若存在)均小于(大于)r。更一般性的特点是:任何一棵二叉树是二叉搜索树,当且仅当其中序遍历序列单调非降。题中提示,左、根、右,没有相等的情况。
方法一:中序遍历
思路:在中序遍历的过程中比较相邻的两个结点值的大小,看是否为非降型。使用队列一次只能看一个结点值的大小,所以需要另外一个变量来保存前一结点的值。代码如下:
1 /** 2 * Definition for binary tree 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 public: 12 bool isValidBST(TreeNode *root) 13 { 14 15 stack<TreeNode *> stk; 16 TreeNode *pre=root; 17 TreeNode *cur=root; 18 19 while(cur|| !stk.empty()) 20 { 21 if(cur) 22 { 23 stk.push(cur); 24 cur=cur->left; 25 } 26 else 27 { 28 cur=stk.top(); 29 stk.pop(); 30 //判断语句 31 if(pre&&cur->val < pre->val) 32 return false; 33 pre=cur; 34 35 cur=cur->right; 36 } 37 } 38 return true; 39 } 40 };
方法二:
可以通过中序遍历将二叉树的结点值存入向量中,然后遍历向量看是否满足非降性。为熟悉递归写法,下面的二叉树的遍历过程为递归版。
1 class Solution { 2 public: 3 bool isValidBST(TreeNode *root) 4 { 5 if(root==NULL) return true; 6 vector<int> nodeVal; 7 inorderTrav(root,nodeVal); 8 for(int i=0;i<nodeVal.size()-1;++i) 9 { 10 if(nodeVal[i]>=nodeVal[i+1]) 11 return false; 12 } 13 14 return true; 15 } 16 17 void inorderTrav(TreeNode *root,vector<int> &nodeVal) 18 { 19 if(root==NULL) return; 20 inorderTrav(root->left,nodeVal); 21 nodeVal.push_back(root->val); 22 inorderTrav(root->right,nodeVal); 23 } 24 };
方法三:整体递归
利用二叉搜索树的特征,左<根<右。参考这里
1 class Solution { 2 public: 3 bool isValidBST(TreeNode *root) 4 { 5 return isValid(root,LONG_MIN,LONG_MAX); 6 } 7 bool isValid(TreeNode * root,long min,long max) 8 { 9 if(root==NULL) return true; 10 if(root->val<=min||root->val>=max) return false; 11 // 左<根 根<右 12 return isValid(root->left,min,root->val)&&isValid(root->right,root->val,max); 13 } 14 };