# 0x00 topic

Given the root node of a binary search tree `root`
and an integer `k`
, please design an algorithm to find `k`the smallest element in it ( `1`counting from )

# 0x01 Ideas

Method 1:
`中序`Traverse the binary search tree
and `数组`save when the last element of the
array is `数量`equal to the smallest`k`
`k`

Method 2:
`中序`Traverse the binary search tree, which is incremental.
Use a marker to record `k`
the first recursion, `k`reduce to `1`
when it is`k` , find the target`0`

# 0x02 solution

language:`Swift`

tree node:`TreeNode`

``````public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
``````

solution:

``````    func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
var res = Int.min
var i = k

func dfs(_ root: TreeNode?) {
guard let r = root else { return }

if i == 0 {
return
}

// 前序遍历位置
dfs(r.left)

// 中序遍历位置
i -= 1
if i == 0 {
res = r.val
}

dfs(r.right)
// 后序遍历位置
}

dfs(root)

return res
}

``````

# Small Wubi application

### Guess you like

Origin blog.csdn.net/xjh093/article/details/123189465
Recommended
Ranking
Daily