LeetCode Weekly Contest 31

LeetCode Weekly Contest 31
Q3 (7)
Give a map with height int, width int; tree []int; squirrel []int; nuts [][]int
Calculate the minimum steps for the squirrel to collect all the nuts and store them in the treenode

func Abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}


func Dis(src[]int, tar[]int) int {
    return Abs(src[0]-tar[0]) + Abs(src[1]-tar[1])
}

func minDistance(height int, width int, tree []int, squirrel []int, nuts [][]int) int {
    moves := 0

    disT := make([]int, 0)
    for _, item := range nuts {
        disT = append(disT, Dis(tree, item))
    }
    
    for index, _ := range nuts {
            moves += 2*disT[index]
    }
    
    min := 0
    for index, item := range nuts {
        dis := Dis(squirrel, item)
        if 0 == min || moves - disT[index] + dis < min {
            min = moves - disT[index] + dis
        }
    }
    
    return min
}

  1. Subtree of Another Tree My SubmissionsBack To Contest
    User Accepted: 798app

User Tried: 912
Total Accepted: 813
Total Submissions: 2000
Difficulty: Easy
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.ide

clipboard.png

clipboard.png

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 
 
 
 

 
 
 
func match(s *TreeNode, t *TreeNode) bool {
    if nil == s && nil == t {
        return true
    }    
    
    if nil == s || nil == t {
        return false
    }
    
    if s.Val != t.Val {
        return false
    }
    
    if true == match(s.Left, t.Left) && true == match(s.Right, t.Right) {
        return true
    }
    if true == match(s.Left, t.Right) && true == match(s.Right, t.Left) {
        return true
    }
    
    return false
} 
 

func dfs(s *TreeNode, t *TreeNode) bool {
    
    if nil == s && nil != t {
        return false
    }
    
    if s.Val == t.Val {
        if true == match(s, t) {
            return true
        }
    }
    
    if true == dfs(s.Left, t) {
            return true
    }
    if true == dfs(s.Right, t) {
            return true
    }

    return false
}

func isSubtree(s *TreeNode, t *TreeNode) bool {
    if nil == t {
        return true
    }
    return dfs(s, t)
}
相關文章
相關標籤/搜索