Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the search problem in binary search Tree by LeetCode

Shulou Source: shulou.com Published: 2022-06-01 13:04:08 09月17日 Update

This article will explain in detail how LeetCode solves the search problem in the binary search tree. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Brief introduction of the problem.

Given the root node and a value of the binary search tree (BST).

You need to find the node in BST where the node value is equal to the given value.

Returns the subtree rooted at this node.

Returns NULL if the node does not exist.

2, example

For example,

Given binary search tree:

4 / 2 7 / 1 3

And value: 2 you should return the following subtree:

2 /\ 1 3 in the above example, if the value you are looking for is 5, but because no node has a value of 5, we should return NULL.

3, the train of thought of solving the problem

The order of Recursive method + binary Tree

4, problem solving procedure

Public class SearchBSTTest {public static void main (String [] args) {TreeNode T1 = new TreeNode (4); TreeNode T2 = new TreeNode (2); TreeNode T3 = new TreeNode (7); TreeNode T4 = new TreeNode (1); TreeNode T5 = new TreeNode (3); t1.left = T2; t1.right = T3; t2.left = T4; t2.right = T5; int val = 2 TreeNode treeNode = searchBST (T1, val); System.out.println ("treeNode =" + treeNode)

}

Public static TreeNode searchBST (TreeNode root, int val) {if (root = = null) {return null;} if (root.val > val) {return searchBST (root.left, val);} else if (root.val < val) {return searchBST (root.right, val);} else {return root;}

5. Picture version of the problem solving program.

This is the end of the article on "LeetCode how to solve the search problem in the binary search tree". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Search nodes questions articles answers more examples programs subtrees good practical ordered content pictures ideas articles methods ordering knowledge recursion Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Information Shulou Tech Info macOS vpn