| by suyi | No comments

Go:二叉搜索树的第k大节点

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var index int
func kthLargest(root *TreeNode, k int) int {
    if root == nil || k < 1{
        return -1
    }
    index = 0
    node := convertToSearch(root, k)
    fmt.Println("====node:" , node)
    return node.Val
}

func convertToSearch(node *TreeNode, k int) *TreeNode{
    if node.Right != nil{
        right := convertToSearch(node.Right, k)
        if right != nil{
            return right
        }
    }

    index ++
    fmt.Println("index:" , index)
    if index == k{
        return node
    }

    if node.Left != nil {
        left := convertToSearch(node.Left, k)
        if left != nil {
            return left
        }
    }

    return nil
}

发表评论