700:二叉搜索树中的搜索

This commit is contained in:
huangge1199 2021-10-26 11:12:06 +08:00
parent 8639b01620
commit 111ed81765
2 changed files with 97 additions and 0 deletions

View File

@ -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)
}

View File

@ -0,0 +1,26 @@
<p>给定二叉搜索树BST的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。</p>
<p>例如,</p>
<pre>
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和值: 2
</pre>
<p>你应该返回如下子树:</p>
<pre>
2
/ \
1 3
</pre>
<p>在上述示例中,如果要找的值是 <code>5</code>,但因为没有节点值为 <code>5</code>,我们应该返回 <code>NULL</code></p>
<div><div>Related Topics</div><div><li></li><li>二叉搜索树</li><li>二叉树</li></div></div><br><div><li>👍 162</li><li>👎 0</li></div>