首页 > 其他 > 详细

leetcode98 Validate Binary Search Tree

时间:2016-01-08 00:15:11      阅读:216      评论: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.

思路:

给子树确定上下界,判断子树根节点值是否在上下界范围内,然后更新上下界。递归实现。

技术分享
 1 /**
 2  * Definition for a binary tree node.
 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)
14             return true;
15         if(judge(root->left,2,0,root->val)&&judge(root->right,1,root->val,0))
16             return true;
17         return false;
18     }
19     
20     bool judge(TreeNode*root,int flag,int a,int b)//flag=0,小于大于;flag=1,大于;flag=2,小于
21     {
22         if(!root)
23             return true;
24         if(flag==0)
25         {
26             if(!(root->val<b&&root->val>a))
27                 return false;
28             if(judge(root->left,0,a,root->val)&&judge(root->right,0,root->val,b))
29                 return true;
30             return false;
31         }
32         if(flag==1)
33         {
34             if(!(root->val>a))
35                 return false;
36             if(judge(root->left,0,a,root->val)&&judge(root->right,1,root->val,0))
37                 return true;
38             return false;
39         }
40         if(flag==2)
41         {
42             if(!(root->val<b))
43                 return false;
44             if(judge(root->left,2,0,root->val)&&judge(root->right,0,root->val,b))
45                 return true;
46             return false;
47         }
48     }
49 };
View Code

 

leetcode98 Validate Binary Search Tree

原文:http://www.cnblogs.com/jsir2016bky/p/5111687.html

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