码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#98 Validate Binary Search Tree

时间:2015-01-29 19:01:22      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!