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

LeetCode: Validata Binary Search Tree

时间:2014-08-28 23:59:16      阅读:421      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   strong   ar   for   

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:

  • The left subtree of a node contains only nodes with keys less than the node‘s key.
  • The right subtree of a node contains only nodes with keys greater than the node‘s key.
  • Both the left and right subtrees must also be binary search trees.

地址: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

标签:des   style   blog   http   color   io   strong   ar   for   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_validate_binary_search_tree.html

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