Given a binary search tree, write a function
kthSmallest
to find the kth smallest element in it.Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Approach
Java
import java.util.ArrayList;import java.util.List;public class KthSmallestElemBST {public static void main(String[] args) {TreeNode root = new TreeNode(3);root.left = new TreeNode(1);root.right = new TreeNode(4);root.left.right = new TreeNode(2);int k = 1;System.out.println(kthSmallest(root, k));}static List<Integer> res;// function to find the kth smallest element in the// treestatic int kthSmallest(TreeNode root, int k) {res = new ArrayList<Integer>();dfs(root);return res.get(k - 1);}static void dfs(TreeNode root) {if (root == null)return;// call for left subtreedfs(root.left);// root datares.add(root.val);// call for right subtreedfs(root.right);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};void dfs(TreeNode *root, vector<int> &res){if (root == NULL)return;//call for left subtreedfs(root->left, res);//root datares.push_back(root->data);//call for right subtreedfs(root->right, res);}//function to find the kth smallest element in the//treeint kthSmallest(TreeNode *root, int k){vector<int> res;dfs(root, res);return res[k - 1];}int main(){TreeNode *root = new TreeNode(3);root->left = new TreeNode(1);root->right = new TreeNode(4);root->left->right = new TreeNode(2);int k = 1;cout << kthSmallest(root, k);}
No comments:
Post a Comment