import (
"math"
"strconv"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
func getHeight(root *TreeNode) int {
if root == nil {
return 0
}
l := getHeight(root.Left)
if l == -1 {
return -1
}
r := getHeight(root.Right)
if r == -1 {
return -1
}
// 求左右高度之差是否大于1,大于1说明不是平衡二叉树
if math.Abs(float64(l-r)) > 1 {
return -1
} else {
return 1 + max(l, r)
}
}
func isBalanced(root *TreeNode) bool {
if getHeight(root) == -1 {
return false
}
return true
}
func getPath(root *TreeNode, p string, res *[]string) {
//判断是不是叶子结点
if root.Left == nil && root.Right == nil {
p = p + strconv.Itoa(root.Val)
*res = append(*res, p)
return
}
p = p + strconv.Itoa(root.Val) + "->"
if root.Left != nil {
getPath(root.Left, p, res)
}
if root.Right != nil {
getPath(root.Right, p, res)
}
}
func binaryTreePaths(root *TreeNode) []string {
res := make([]string, 0)
getPath(root, "", &res)
return res
}
func sumOfLeftLeaves(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return 0
}
l := sumOfLeftLeaves(root.Left)
//判断左子树的左孩子是不是叶子结点,是叶子节点则获取左孩子的值
if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
l = root.Left.Val
}
r := sumOfLeftLeaves(root.Right)
return l + r
}