检查是否为BST
题目描述
请实现一个函数,检查一棵二叉树是否为二叉查找树。
给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树。
思路一:递归解法,其实大部分二叉树问题均可采用递归来解决,本题也不例外。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Checker { public: bool checkBST(TreeNode* root) { // write code here if(root==NULL) return true; if(root->left!=NULL){ if(root->left->val > root->val) return false; if(root->left->right!= NULL && root->left->right->val > root->val) return false; } if(root->right!=NULL ) { if(root->right->val < root->val) return false; if(root->right->left!= NULL && root->right->left->val < root->val) return false; } return checkBST(root->left) && checkBST(root->right); } };
思路二:考虑到二叉查找树中序遍历后是一个递增数组,依据此来进行判定。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Checker { public: vector<int> vec; void inorder(TreeNode* root){ if(root){ inorder(root->left); vec.push_back(root->val); inorder(root->right); } } bool checkBST(TreeNode* root) { // write code here if(root==NULL) return true; inorder(root); for(int i=0,len = vec.size()-1;i<len;i++){ if(vec[i] > vec[i+1]) return false; } return true; } };
递归算法有可能会导致栈溢出(stackoverflow),而中序遍历然后判断数组的方法其空间复杂度为O<n>。如何才能进一步降低空间时间复杂度,求民间牛人。
posted on 2016-06-13 15:11 echoorchid 阅读(134) 评论(0) 编辑 收藏 举报