代码随想录算法训练营Day20 | 110.平衡二叉树、257.二叉树的所有路径、404.左叶子之和

62 阅读1分钟

LeetCode题目

110.平衡二叉树

题目链接:Balanced Binary Tree - LeetCode

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func Abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func getHeight(node *TreeNode) int {
	if node == nil {
		return 0
	}
	leftHeight := getHeight(node.Left)
	if leftHeight == -1 {
		return -1
	}
	rightHeight := getHeight(node.Right)
	if rightHeight == -1 {
		return -1
	}
	if Abs(leftHeight-rightHeight) > 1 {
		return -1
	} else {
		return 1 + max(leftHeight, rightHeight)
	}
}

func isBalanced(root *TreeNode) bool {
	if getHeight(root) == -1 {
		return false
	}
	return true
}

257.二叉树的所有路径

题目链接:Binary Tree Paths - LeetCode

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func traversal(cur *TreeNode, path *[]int, result *[]string) {
	*path = append(*path, cur.Val)
	if cur.Left == nil && cur.Right == nil {
		sPath := ""
		for i := 0; i < len(*path)-1; i++ {
			sPath += strconv.Itoa((*path)[i])
			sPath += "->"
		}
		sPath += strconv.Itoa((*path)[len(*path)-1])
		*result = append(*result, sPath)
		return
	}
	if cur.Left != nil {
		traversal(cur.Left, path, result)
		*path = (*path)[:len(*path)-1]
	}
	if cur.Right != nil {
		traversal(cur.Right, path, result)
		*path = (*path)[:len(*path)-1]
	}
}

func binaryTreePaths(root *TreeNode) []string {
	result := make([]string, 0)
	path := make([]int, 0)
	if root == nil {
		return result
	}
	traversal(root, &path, &result)
	return result
}

404.左叶子之和

题目链接:Sum of Left Leaves - LeetCode

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumOfLeftLeaves(root *TreeNode) int {
	if root == nil {
		return 0
	}
	leftValue := 0
	if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
		leftValue = root.Left.Val
	}
	return leftValue + sumOfLeftLeaves(root.Left) + sumOfLeftLeaves(root.Right)
}