In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.