首页 > 其他 > 详细

LeetCode 98 Validate Binary Search Tree判断是否为合法二叉树

时间:2016-02-12 15:07:51      阅读:554      评论:0      收藏:0      [点我收藏+]
 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 Left(TreeNode* left, int root){
13         while(left->right != NULL){
14             left = left->right;
15         }
16         return left->val < root;
17     }
18     bool Right(TreeNode* right,int root){
19         while(right->left != NULL)
20             right = right->left;
21         return right->val > root;
22     }
23     
24     bool isValidBST(TreeNode* root) {
25         if(root == NULL) return true;
26         int left = 0, right = 0;
27         bool lres = true,rres = true;
28         if(root->left){//不为空的情况下
29             left = 1;
30             if(root->left->val >= root->val) return false;
31             lres = isValidBST(root->left);
32             if(lres) lres = Left(root->left,root->val);//在左儿子是合法二叉树的情况下,检验左儿子的最大值(即一直取左儿子的右儿子)是否小于root值
33             else return false;
34         }
35         if(root->right){
36             right = 1;
37             if(root->right->val <= root->val) return false;
38             rres = isValidBST(root->right);
39             if(rres) rres = Right(root->right,root->val);
40             else return false;
41         }
42         return lres && rres;
43     }
44     
45 };

合法二叉树条件:1、左儿子均小于根,右儿子均大于根 2、左儿子、右儿子均为合法二叉树

LeetCode 98 Validate Binary Search Tree判断是否为合法二叉树

原文:http://www.cnblogs.com/co0oder/p/5187035.html

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