您的位置:首页 > 其它

leetcode Validate Binary Search Tree

2013-12-18 20:44 423 查看
中序遍历得到所有的顺序之后只需要比较相邻的两个结点是否有序就可以了!

/**

* Definition for binary tree

* struct TreeNode {

* int val;

* TreeNode *left;

* TreeNode *right;

* TreeNode(int x) : val(x), left(NULL), right(NULL) {}

* };

*/

class Solution {

public:

bool isValidBST(TreeNode *root) {

// IMPORTANT: Please reset any member data you declared, as

// the same Solution instance will be reused for each test case.

if(root==NULL)return true;

TreeNode * fa = NULL;

return solve(root,fa);

}

private:

bool solve(TreeNode *root,TreeNode * &fa){

if(root==NULL)return true;

bool ok = solve(root->left,fa);

if(!ok)return ok;

if(fa==NULL || fa->val<root->val){

fa = root;

return solve(root->right,fa);

}else return false;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: