From 111ed81765583dff5bea8cab417fc004d56601e9 Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Tue, 26 Oct 2021 11:12:06 +0800 Subject: [PATCH] =?UTF-8?q?700:=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E4=B8=AD=E7=9A=84=E6=90=9C=E7=B4=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../editor/cn/SearchInABinarySearchTree.java | 71 +++++++++++++++++++ .../doc/content/SearchInABinarySearchTree.md | 26 +++++++ 2 files changed, 97 insertions(+) create mode 100644 src/main/java/leetcode/editor/cn/SearchInABinarySearchTree.java create mode 100644 src/main/java/leetcode/editor/cn/doc/content/SearchInABinarySearchTree.md diff --git a/src/main/java/leetcode/editor/cn/SearchInABinarySearchTree.java b/src/main/java/leetcode/editor/cn/SearchInABinarySearchTree.java new file mode 100644 index 0000000..e24a510 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/SearchInABinarySearchTree.java @@ -0,0 +1,71 @@ +//给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 +// +// 例如, +// +// +//给定二叉搜索树: +// +// 4 +// / \ +// 2 7 +// / \ +// 1 3 +// +//和值: 2 +// +// +// 你应该返回如下子树: +// +// +// 2 +// / \ +// 1 3 +// +// +// 在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。 +// Related Topics 树 二叉搜索树 二叉树 👍 162 👎 0 + +package leetcode.editor.cn; + +import com.code.leet.entiy.TreeNode; + +//700:二叉搜索树中的搜索 +class SearchInABinarySearchTree { + public static void main(String[] args) { + //测试代码 + Solution solution = new SearchInABinarySearchTree().new Solution(); + } + + //力扣代码 + //leetcode submit region begin(Prohibit modification and deletion) + + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + class Solution { + public TreeNode searchBST(TreeNode root, int val) { + while (root != null && root.val != val) { + if (root.val > val) { + root = root.left; + } else { + root = root.right; + } + } + return root; + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file diff --git a/src/main/java/leetcode/editor/cn/doc/content/SearchInABinarySearchTree.md b/src/main/java/leetcode/editor/cn/doc/content/SearchInABinarySearchTree.md new file mode 100644 index 0000000..cc038a6 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/doc/content/SearchInABinarySearchTree.md @@ -0,0 +1,26 @@ +

给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。

+ +

例如,

+ +
+给定二叉搜索树:
+
+        4
+       / \
+      2   7
+     / \
+    1   3
+
+和值: 2
+
+ +

你应该返回如下子树:

+ +
+      2     
+     / \   
+    1   3
+
+ +

在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL

+
Related Topics
  • 二叉搜索树
  • 二叉树

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