标签:
中序遍历二叉树,如果出现逆序对,则说明不是合法BST
代码:
1 bool isValidBST(TreeNode *root) { 2 stack<TreeNode *> st; 3 int last = 0; 4 bool hasLast = false; 5 TreeNode *node = NULL; 6 7 node = root; 8 while (node) { 9 while (node) { 10 st.push(node); 11 node = node->left; 12 } 13 node = NULL; 14 while (!st.empty() && !node) { 15 if (hasLast && st.top()->val <= last) 16 return false; 17 hasLast = true; 18 last = st.top()->val; 19 node = st.top()->right; 20 st.pop(); 21 } 22 } 23 24 return true; 25 }
Leetcode#98 Validate Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/boring09/p/4260409.html