LeetCode: Validata Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
地址:https://oj.leetcode.com/problems/validate-binary-search-tree/
算法:中序遍历,看看遍历到的节点值是否递增。代码:
 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*> stk;
15         TreeNode *p = root;
16         while(p){
17             stk.push(p);
18             p = p->left;
19         }
20         TreeNode *pre = NULL;
21         p = NULL;
22         while(!stk.empty()){
23             pre = p;
24             p = stk.top();
25             stk.pop();
26             if(pre && p->val <= pre->val){
27                 return false;
28             }
29             if(p->right){
30                 TreeNode *q = p->right;
31                 while(q){
32                     stk.push(q);
33                     q = q->left;
34                 }
35             }
36         }
37         return true;
38     }
39 };
LeetCode: Validata Binary Search Tree
原文:http://www.cnblogs.com/boostable/p/leetcode_validate_binary_search_tree.html