101. 对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
func isSymmetric(root *TreeNode) bool {
if root == nil{ return true}
return judge(root.Left,root.Right)
}
func judge(lf *TreeNode , ri *TreeNode)bool{
if lf == nil && ri ==nil{ return true}
if lf == nil || ri ==nil{ return false}
if lf.Val != ri.Val{return false}
return judge(lf.Left,ri.Right) && judge(lf.Right,ri.Left)
}
102. 二叉树的层序遍历
var arr [][]int
func levelOrder(root *TreeNode) [][]int {
arr= [][]int{}
depth:=0
order(root,depth)
return arr
}
func order(root *TreeNode,depth int){
if root ==nil{return }
if len(arr) == depth{arr = append(arr,[]int{})} //这个地方是因为要追加一个新的数组来保存该层的节点元素
arr[depth] = append(arr[depth],root.Val)
order(root.Left,depth+1)
order(root.Right,depth+1)
}
226. 翻转二叉树
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
func invertTree(root *TreeNode) *TreeNode {
if root == nil { return nil }
root.Left ,root.Right = root.Right,root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}