学习目标:
- 完成 LeetCode 简单 级别 226 题
学习内容:
- LeetCode 题目 226
学习时间:
- 2022.07.01 16:00 PM
学习产出:
- 题解
看到二叉树首先就想到了回溯,想要反转二叉树也较为简单,将每个树节点的左右子树进行交换即可,所以在回溯的过程中交换左右子树,节点为空时结束回溯,实现代码如下。
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
var Inv func(t *TreeNode)
Inv = func(t *TreeNode){
if t.Left!=nil{
Inv(t.Left)
}
if t.Right!=nil{
Inv(t.Right)
}
tmp:=t.Left
t.Left = t.Right
t.Right = tmp
}
if root!=nil{
Inv(root)
}
return root
}