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.
地址:
算法:中序遍历,看看遍历到的节点值是否递增。代码:
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 stackstk;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 };
posted on 2014-08-28 22:29 阅读( ...) 评论( ...)