标签:des style blog http color io strong ar for
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
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 };
标签:des style blog http color io strong ar for
原文地址:http://www.cnblogs.com/bugfly/p/3942291.html