LeetCode - Easy - 700. Search in a Binary Search Tree

Topic

  • Tree

Description

https://leetcode.com/problems/search-in-a-binary-search-tree/

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.

Example 1:

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Example 2:

Input: root = [4,2,7,1,3], val = 5
Output: []

Constraints:

  • The number of nodes in the tree is in the range [ 1 , 5000 ] [1, 5000] [1,5000].
  • 1 < = N o d e . v a l < = 1 0 7 1 <= Node.val <= 10^7 1<=Node.val<=107
  • root is a binary search tree.
  • 1 < = v a l < = 1 0 7 1 <= val <= 10^7 1<=val<=107

Analysis

方法一:递归法

方法二:迭代法

Submission

import com.lun.util.BinaryTree.TreeNode;

public class SearchInABinarySearchTree {
	
	//方法一:递归法
    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null) return null;
    	
    	if(val < root.val)
    		return searchBST(root.left, val);
    	else if(root.val < val)
    		return searchBST(root.right, val);
    	else 
    		return root;
    }
    
    //方法二:迭代法
    public TreeNode searchBST2(TreeNode root, int val) {
    	TreeNode p = root;
    	
    	while(p != null) {
    		if(val < p.val) {
    			p = p.left;
    		}else if(val > p.val){
    			p = p.right;
    		}else {
    			return p;
    		}
    	}
    	
    	return null;
    } 
    
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;

public class SearchInABinarySearchTreeTest {

	@Test
	public void test() {
		SearchInABinarySearchTree obj = new SearchInABinarySearchTree();

		TreeNode root = BinaryTree.integers2BinaryTree(4,2,7,1,3);
		TreeNode expected = BinaryTree.integers2BinaryTree(2,1,3);
		
		assertTrue(BinaryTree.equals(obj.searchBST(root, 2), expected));
		assertNull(obj.searchBST(root, 5));
	}
	
	@Test
	public void test2() {
		SearchInABinarySearchTree obj = new SearchInABinarySearchTree();
		
		TreeNode root = BinaryTree.integers2BinaryTree(4,2,7,1,3);
		TreeNode expected = BinaryTree.integers2BinaryTree(2,1,3);
		
		assertTrue(BinaryTree.equals(obj.searchBST2(root, 2), expected));
		assertNull(obj.searchBST2(root, 5));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值