专栏首页皮皮瞎学编程Tree - 226. Invert Binary Tree

Tree - 226. Invert Binary Tree

226. Invert Binary Tree

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

思路:

递归求解翻转每个不为nil的节点

代码:

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 root }
    
    root.Left, root.Right = root.Right, root.Left
    invertTree(root.Left)
    invertTree(root.Right)
    
    return root
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Tree - 235. Lowest Common Ancestor of a Binary Search Tree

    235. Lowest Common Ancestor of a Binary Search Tree

    用户5705150
  • Tree - 337. House Robber III

    The thief has found himself a new place for his thievery again. There is only on...

    用户5705150
  • Tree - 104. Maximum Depth of Binary Tree

    Given a binary tree, find its maximum depth.

    用户5705150
  • Golang Leetcode 226. Invert Binary Tree.go

    版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89043397

    anakinsun
  • Golang Leetcode 337. House Robber III.go

    版权声明:原创勿转 https://blog.csdn.net/anakinsun/arti...

    anakinsun
  • 二叉树的最近公共祖先 Lowest Common Ancestor of a Binary Tree

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in...

    爱写bug
  • LeetCode 146 LRU Cache

    实现一个缓存机制。很多人的写法都是使用HashTable, Map,Dictionary 或者别的工具。

    ShenduCC
  • 如何在CDH集群安装Anaconda&搭建Python私有源

    Anaconda是一个用于科学计算的Python发行版,支持 Linux, Mac, Windows系统,提供了包管理与环境管理的功能,可以很方便地解决多版本p...

    Fayson
  • Golang Leetcode 669. Trim a Binary Search Tree.go

    更多内容请移步我的repo:https://github.com/anakin/golang-leetcode

    anakinsun
  • 组复制常规操作-使用xtrabackup备份恢复或添加组成员 | 全方位认识MySQL8.0 Group Replication

    xtrabackup 8.0版本支持备份时不加全局读锁(不执行FLUSH TABLE WITH READ LOCK语句),这就避免了在组复制中启用多线程回放的组...

    老叶茶馆

扫码关注云+社区

领取腾讯云代金券