In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how LeetCode finds the smallest element in the binary search tree, which is very detailed and has a certain reference value. Friends who are interested must read it!
1. Brief introduction of the problem.
Given a binary search tree, write a function kthSmallest to find the k smallest element in it.
Explanation: you can assume that k is always valid, 1 ≤ k ≤ binary search tree number of elements.
2, example
Example 1:
Input: root = [3Person1Magol 4jnullMagne2], k = 1 3 /\ 1 4\ 2 output: 1 example 2:
Input: root = [5, 3, 6, 6, 2, 4, and 4], k = 3 5 /\ 3 6 /\ 2 4 / 1 output: 3.
3, the train of thought of solving the problem
Use the middle order traversal method of binary tree to solve the problem.
4, problem solving procedure
Import java.util.ArrayList;import java.util.List
Public class KthSmallestTest3 {public static void main (String [] args) {TreeNode T1 = new TreeNode (3); TreeNode T2 = new TreeNode (1); TreeNode T3 = new TreeNode (4); TreeNode T4 = new TreeNode (2); t1.left = T2; t1.right = T3; t2.right = T4; int k = 1; int kthSmallest = kthSmallest (T1, k) System.out.println ("kthSmallest =" + kthSmallest)
}
Private static List list = new ArrayList ()
Public static int kthSmallest (TreeNode root, int k) {if (root = = null) {return 0;} dfs (root); return list.get (k-1);}
Private static void dfs (TreeNode root) {if (root = = null) {return;} if (root.left! = null) {dfs (root.left)
} list.add (root.val); if (root.right! = null) {dfs (root.right);}
5. Picture version of the problem solving program.
The above is all the content of the article "how to find the K-smallest element in the binary search tree by LeetCode". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.