Day 17 二叉树Part04
110. 平衡二叉树 - 力扣(LeetCode)
分别计算左右子树的高度即可,
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
var hight, l, r int
var compare func (*TreeNode, int) int
compare = func (root *TreeNode, h int) int {
if root == nil {
return h
}
h++
l, r = compare(root.Left, h), compare(root.Right, h)
fmt.Println(l, r)
if l == -1 || r == -1 { // 等于-1即不成立
return -1
}
if balance(l, r) {
return max(l, r)
} else {
return -1
}
}
return compare(root, hight) != -1
}
func balance(a, b int) bool { // 平衡条件
return a - b < 2 && b - a < 2
}
func max(a, b int) int { // 返回最深的深度
if a > b {
return a
}
return b
}
257. 二叉树的所有路径 - 力扣(LeetCode)
基本也还是遍历,转换字符串稍稍麻烦点
var paths []string
func binaryTreePaths(root *TreeNode) []string {
paths = []string{}
constructPaths(root, "")
return paths
}
func constructPaths(root *TreeNode, path string) {
if root != nil {
pathSB := path
pathSB += strconv.Itoa(root.Val) // 整型转化为字符串
if root.Left == nil && root.Right == nil {
paths = append(paths, pathSB)
} else {
pathSB += "->"
constructPaths(root.Left, pathSB)
constructPaths(root.Right, pathSB)
}
}
}
404. 左叶子之和 - 力扣(LeetCode)
左叶子,不是左节点,这个有点小烦人
func sumOfLeftLeaves(root *TreeNode) int {
var sum int
var sonLeft func(root *TreeNode)
sonLeft = func(root *TreeNode) {
// fmt.Println(sum)
if root.Left != nil {
if root.Left.Left == nil && root.Left.Right == nil {
sum += root.Left.Val
}
sonLeft(root.Left)
}
if root.Right != nil {
sonLeft(root.Right)
}
}
sonLeft(root)
return sum
}