題目
給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。
假設一個二叉搜索樹具有如下特徵:
- 節點的左子樹只包含小於當前節點的數。
- 節點的右子樹只包含大於當前節點的數。
- 所有左子樹和右子樹自身必須也是二叉搜索樹。
示例 1:
輸入:
2
/ \
1 3
輸出: true
示例 2:
輸入:
5
/ \
1 4
/ \
3 6
輸出: false
解釋: 輸入爲: [5,1,4,null,null,3,6]。
根節點的值爲 5 ,但是其右子節點值爲 4 。
題解
這道題目主要是利用二叉搜索樹的一個性質:
二叉搜索樹的中序遍歷結果是一個升序的序列。
那麼問題轉變成:中序遍歷 + 驗證是不是升序.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> inPrint(TreeNode root, List<Integer> res) {
if (root != null) {
inPrint(root.left, res);
res.add(root.val);
inPrint(root.right, res);
}
return res;
}
public boolean isValidBST(TreeNode root) {
List<Integer> res = inPrint(root, new LinkedList<>());
if (res.size() == 1) {
return true;
}
for (int i = 1; i < res.size(); i++) {
if (res.get(i) <= res.get(i - 1)) {
return false;
}
}
return true;
}
}