反转二叉树
type NoteTree struct {
Val int
left *NoteTree
right *NoteTree
}
// 从根部往下,依次递归反转
func reverse_notetree(root *NoteTree) *NoteTree {
if root == nil{
return nil
}
left := reverse_notetree(root.left)
right := reverse_notetree(root.right)
root.left = right
root.right = left
return root
}
测试
func main() {
root :=&NoteTree{}
left1 :=&NoteTree{}
right1 :=&NoteTree{}
left2 :=&NoteTree{}
right2 :=&NoteTree{}
left21 :=&NoteTree{}
right21 :=&NoteTree{}
root.Val = 0
root.left = left1
root.right = right1
left1.Val = 1
left1.left = left2
left1.right = right2
right1.Val = 2
right1.left = left21
right1.right = right21
left2.Val = 3
right2.Val = 4
left2.left = nil
right2.right = nil
left21.Val = 5
right21.Val = 6
left21.left = nil
right21.right = nil
root1 := reverse_notetree(root)
fmt.Println(root1.Val)
fmt.Println(root1.left.Val)
fmt.Println(root1.left.left.Val)
}
0
2
6
有疑问加站长微信联系(非本文作者)