反转二叉树

题目:

示例:

输入:

   4

   /   \
  2     7
 / \   / \
1   3 6   9
输出:

   4

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

解题思路:

因为树具有天然的递归结构,关于树的问题,我们常用递归来实现。

翻转二叉树,我们首先判断如果反转一颗空树结果还是一颗空树。

如果不是空树,就将父节点的左右节点交换,并进行递归。

//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
    }
    // tmp := root.Left
    // root.Left = root.Right
    // root.Right = tmp
    root.Left, root.Right = root.Right, root.Left // go语法交换元素,等价于上面3行代码
    root.Left = invertTree(root.Left) // 递归左子树
    root.Right = invertTree(root.Right) // 递归柚子树
    return root
}

  地址:https://mp.weixin.qq.com/s/bMqbrSY4RV_T4BPdOz8uWg

posted @ 2020-07-13 10:44  small_lei_it  阅读(320)  评论(0编辑  收藏  举报