Leetcode - Kth Smallest Element in a BST
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1
Inorder to trasversal the tree, and then find the k-th position.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func kthSmallest(root *TreeNode, k int) int { //count := 0 stack := []*TreeNode{} node := root for node != nil || len(stack) != 0 { for node != nil { stack = append(stack, node) node = node.Left } if len(stack) != 0 { node = stack[len(stack)-1] k-- if k == 0 { return node.Val } stack = stack[:len(stack)-1] node = node.Right } } return 0 }