首页 > 其他 > 详细

Validate Binary Search Tree

时间:2014-04-07 04:04:05      阅读:476      评论:0      收藏:0      [点我收藏+]

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.

Solution: Recursion. 1. Add lower & upper bound. O(n)
2. Inorder traversal with one additional parameter (value of predecessor). O(n)

bubuko.com,布布扣
 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         int val = INT_MIN;
14         return isValidBSTRe(root, val);
15     }
16     
17     bool isValidBSTRe(TreeNode* root, int& val)
18     {
19         if(!root) return true;
20         
21         if(root->left && !isValidBSTRe(root->left, val))
22             return false;
23         if(root->val <= val) 
24             return false;
25         val = root->val;
26         if(root->right && !isValidBSTRe(root->right, val))
27             return false;
28         return true;
29     }
30 };
bubuko.com,布布扣

 

Validate Binary Search Tree,布布扣,bubuko.com

Validate Binary Search Tree

原文:http://www.cnblogs.com/zhengjiankang/p/3649673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!