LeetCode知识点总结 - 700

这篇博客介绍了LeetCode第700题的解决方案,题目要求在给定的二叉搜索树中寻找等于给定值的节点,并返回该节点作为根的子树。通过利用二叉搜索树的特性,我们可以从根节点开始,如果值小于当前节点则遍历左子树,如果值大于当前节点则遍历右子树,找到匹配值的节点后返回。
摘要由CSDN通过智能技术生成

LeetCode 700. Search in a Binary Search Tree

考点难度
TreeEasy
题目

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

思路

利用left child小于parent,right child大于parent的性质找到和val相等的parent。

答案
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
		while (root != null)
		{
			if ( val < root.val ) root = root.left;
			else if ( val > root.val ) root = root.right;
			else return root;
		}
		return root;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值