diff --git a/src/main/java/leetcode/editor/cn/LegalBinarySearchTreeLcci.java b/src/main/java/leetcode/editor/cn/LegalBinarySearchTreeLcci.java new file mode 100644 index 0000000..d01b495 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/LegalBinarySearchTreeLcci.java @@ -0,0 +1,49 @@ +//

实现一个函数,检查一棵二叉树是否为二叉搜索树。

示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
Related Topics
  • 深度优先搜索
  • 二叉搜索树
  • 二叉树

  • 👍 76
  • 👎 0
  • +package leetcode.editor.cn; + +import com.code.leet.entiy.TreeNode; + +// 面试题 04.05:合法二叉搜索树 +public class LegalBinarySearchTreeLcci { + public static void main(String[] args) { + Solution solution = new LegalBinarySearchTreeLcci().new Solution(); + // TO TEST + } + //leetcode submit region begin(Prohibit modification and deletion) + + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + public boolean isValidBST(TreeNode root) { + return dfs(root, null, null); + } + + public boolean dfs(TreeNode node, Integer lower, Integer upper) { + if (node == null) { + return true; + } + + int val = node.val; + if (lower != null && val <= lower) { + return false; + } + if (upper != null && val >= upper) { + return false; + } + + if (!dfs(node.right, val, upper)) { + return false; + } + return dfs(node.left, lower, val); + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} diff --git a/src/main/java/leetcode/editor/cn/doc/content/LegalBinarySearchTreeLcci.md b/src/main/java/leetcode/editor/cn/doc/content/LegalBinarySearchTreeLcci.md new file mode 100644 index 0000000..f7fecfc --- /dev/null +++ b/src/main/java/leetcode/editor/cn/doc/content/LegalBinarySearchTreeLcci.md @@ -0,0 +1 @@ +

    实现一个函数,检查一棵二叉树是否为二叉搜索树。

    示例 1:
    输入:
    2
    / \
    1 3
    输出: true
    示例 2:
    输入:
    5
    / \
    1 4
      / \
      3 6
    输出: false
    解释: 输入为: [5,1,4,null,null,3,6]。
      根节点的值为 5 ,但是其右子节点值为 4 。
    Related Topics
  • 深度优先搜索
  • 二叉搜索树
  • 二叉树

  • 👍 76
  • 👎 0
  • \ No newline at end of file