題解:
/**
* * definition for a binary tree node.
* * struct treenode
* * };
* */
class solution
// 思路是判斷當前節點值,是否在區間 lower->val <= root->val <= upper->val
bool pre_order(treenode* root, treenode* lower, treenode* upper)
if(lower != nullptr && root->val <= lower->val) return false;
if(upper != nullptr && root->val >= upper->val) return false;
return pre_order(root->left, lower, root)
&& pre_order(root->right, root, upper);}};
/**
* definition for a binary tree node.
* struct treenode
* treenode(int x) : val(x), left(nullptr), right(nullptr) {}
* treenode(int x, treenode *left, treenode *right) : val(x), left(left), right(right) {}
* };
*/class solution
};bool isvalidbst(treenode* root)
result is_bst(treenode* root)
// 獲得以root->left為根節點的結果
result left = is_bst(root->left);
if (!left.bst)
// 獲得以root->right為根節點的結果
result right = is_bst(root->right);
if (!right.bst)
if ((root->left && left.max_val >= root->val) ||
(root->right && right.min_val <= root->val))
return result(true, max(right.max_val, root->val), min(left.min_val, root->val));}};
/**
* * definition for a binary tree node.
* * struct treenode
* * };
* */
class solution
// 二叉排序樹的中序遍歷是有序的,從小到大
bool in_order(treenode* root)
if(!in_order(root->left))
// 判斷當前元素和前乙個元素的大小比較
if(pre != nullptr && pre->val >= root->val)
pre = root;
return in_order(root->right);}};
public class solution
treenode lastnode = null;
while (!stack.isempty())
lastnode = node;
// move to next
if (node.right == null)
} else }}
return true;}}
98 驗證二叉搜尋樹
給定乙個二叉樹,判斷其是否是乙個有效的二叉搜尋樹。假設乙個二叉搜尋樹具有如下特徵 節點的左子樹只包含小於當前節點的數。節點的右子樹只包含大於當前節點的數。所有左子樹和右子樹自身必須也是二叉搜尋樹。示例 1 輸入 2 1 3 輸出 true 示例 2 輸入 5 1 4 3 6 輸出 false 解釋 ...
98 驗證二叉搜尋樹
給定乙個二叉樹,判斷其是否是乙個有效的二叉搜尋樹。假設乙個二叉搜尋樹具有如下特徵 示例 1 輸入 2 1 3 輸出 true示例 2 輸入 5 1 4 3 6 輸出 false 解釋 輸入為 5,1,4,null,null,3,6 根節點的值為 5 但是其右子節點值為 4 import sys cl...
98 驗證二叉搜尋樹
98.驗證二叉搜尋樹 分析這道驗證二叉搜尋樹有很多種解法,可以利用它本身的性質來做,即左 根 右,也可以通過利用中序遍歷結果為有序數列來做,下面我們先來看最簡單的一種,就是利用其本身性質來做,初始化時帶入系統最大值和最小值,在遞迴過程中換成它們自己的節點值,用long代替int就是為了包括int的邊...