[Binary tree] The K-th smallest element in a binary search tree

0x00 topic

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


0x01 Ideas

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

Method 2:
中序Traverse the binary search tree, which is incremental.
Use a marker to record k
the first recursion, kreduce to 1
when it isk , find the target0


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

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/123189465