首页 > 其他 > 详细

Leetcode#98 Validate Binary Search Tree

时间:2015-01-29 18:59:43      阅读:254      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!