美文网首页
226. 翻转二叉树

226. 翻转二叉树

作者: 7赢月 | 来源:发表于2023-03-03 16:03 被阅读0次

有一个想法其实很不错,使用递归的方法,把每层的值都进行交换

这样就自然形成了一棵树的全部翻转

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
    if root == nil{
        return root
    }
    if root.Left == nil && root.Right==nil{
        return root
    }
    var ret = root.Left
    root.Left = root.Right
    root.Right = ret
    invertTree(root.Left)
    invertTree(root.Right)
    return root
}

相关文章

网友评论

      本文标题:226. 翻转二叉树

      本文链接:https://www.haomeiwen.com/subject/xcxeldtx.html