2019-10-27

Find Bottom Left Tree Value

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

/**
深度优先搜索整个树,记录层数
每次搜索的时候,第一个碰到的元素,就是该层的最左子树
*/
var maxd, val int

func findBottomLeftValue(root *TreeNode) int {
    maxd = 0
    val = 0
    dfs(root, 1)
    return val
}

func dfs(root *TreeNode, d int) {
    if root == nil {
        return
    }
    if d > maxd {
        maxd = d
        val = root.Val
    }
    if root.Left != nil {
        dfs(root.Left, d+1)
    }
    if root.Right != nil {
        dfs(root.Right, d+1)
    }

}

ZigZag Conversion

/**
关键是要算出循环的长度:
为 row + row -2
*/
func convert(s string, numRows int) string {
    if numRows == 1 {
        return s
    }

    item_len := 2*numRows - 2 //循环的长度
    res := make([][]string, numRows, numRows)

    for index, v := range s {

        mod := index % item_len

        if mod < numRows {
            res[mod] = append(res[mod], string(v))
        } else {
            i := numRows - (mod - numRows) - 2
            res[i] = append(res[i], string(v))
        }
    }

    var str string

    for _, arr := range res {
        for _, v := range arr {
            str += v
        }
    }

    return str
}

Count and Say

func countAndSay(n int) string {
    if n == 1 {
        return "1"
    }
    return count(countAndSay(n - 1))
}

func count(s string) string {
    c := string(s[0])
    count := 1
    res := ""
    for _, char := range s[1:] {
        if string(char) == c {
            count += 1
        } else {
            res = res + strconv.Itoa(count) + string(c)
            c = string(char)
            count = 1
        }
    }
    res = res + strconv.Itoa(count) + string(c)
    return res
}

你可能感兴趣的:(2019-10-27)