原題地址:https://leetcode.com/problems/validate-binary-search-tree/description/
題目描述
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.
例子就不貼了纬傲。就是要判斷一棵二叉樹是不是有效的搜索樹满败,即左子節(jié)點(diǎn)的值小于父節(jié)點(diǎn)的值,右子節(jié)點(diǎn)的值大于父節(jié)點(diǎn)的值叹括。
思路
一開始我寫了一個(gè)DFS,在遍歷的時(shí)候檢查每單個(gè)父節(jié)點(diǎn)和它的兩個(gè)子節(jié)點(diǎn)的大小關(guān)系宵荒,但是即便每個(gè)父節(jié)點(diǎn)都符合這樣的檢查條件仍然可能是無效的搜索樹汁雷,如圖
失敗樣例.png
元素6
這個(gè)節(jié)點(diǎn)就不該出現(xiàn)在右邊的子樹上净嘀,因?yàn)?小于10。
之后我的做法是侠讯,對(duì)符合題目條件的有效搜索樹進(jìn)行中序遍歷挖藏,判斷所得到的數(shù)組是不是已經(jīng)有序了(遞增)。如果是則返回true
厢漩,不是則返回false
膜眠。
代碼
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> result;
void travelInorder(TreeNode* root){
if(root!=NULL){
travelInorder(root->left);
result.push_back(root->val);
travelInorder(root->right);
}
}
bool isValidBST(TreeNode* root) {
if(root==NULL){
return true;
}
travelInorder(root);
for(int i =0 ;i<result.size()-1;i++){
if(result[i]>=result[i+1]){
return false;
}
}
return true;
}
};
運(yùn)行時(shí)間擊敗了%39.21
的人。
踩坑
要注意的地方就是出現(xiàn)相等的元素算無效搜索樹溜嗜,以及輸入可能為空宵膨。