Leetcode#98 Validate Binary Search Tree

原题地址

 

中序遍历二叉树,如果出现逆序对,则说明不是合法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 }

 

posted @ 2015-01-29 17:11  李舜阳  阅读(120)  评论(0编辑  收藏  举报