首页 > 代码库 > Validate Binary Search Tree

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.

 

中序遍历这棵树,如果前驱大于等于当前节点,那么就不是bst树

 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         if( !root ) return true;14         stack<TreeNode*> st;15         TreeNode* cur = root;16         while( cur ) {17             st.push(cur);18             cur = cur->left;19         }20         TreeNode* pre = 0;21         while( !st.empty() ) {22             cur = st.top();23             st.pop();24             if( pre && pre->val >= cur->val ) return false;25             pre = cur;26             cur = cur->right;27             while( cur ) {28                 st.push(cur);29                 cur = cur->left;30             }31         }32         return true;33     }34 };

 

Validate Binary Search Tree