时间复杂度:O(n)
解题思路
后序遍历,先左右交换叶子结点,然后逐渐向上交换。交换左右节点就是翻转的实现。
AC代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root==nil{
return nil
}
invertTree(root.Left)
invertTree(root.Right)
root.Left,root.Right=root.Right,root.Left
return root
}
感悟
一开始是单独写一个函数实现翻转,因为题目要求返回根节点嘛。看了题解反应过来哪需要那么麻烦……