文章目录
226. 翻转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例 2:

输入:root = [2,1,3]
输出:[2,3,1]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目范围在 [0, 100] 内
- -100 <= Node.val <= 100
解题思路
递归的翻转每个节点的左右孩子便会完成整棵树的翻转
Go代码
/**
* 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
}
if root.Left != nil {
invertTree(root.Left)
}
root.Left,root.Right = root.Right,root.Left
if root.Left != nil{ // 注意 这里依然要遍历左孩子,因为中间节点已经翻转了
invertTree(root.Left)
}
return root
}

670

被折叠的 条评论
为什么被折叠?



