How does LeetCode find the smallest element in a binary search tree?
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!