essay

hot100-翻转二叉树

#算法

hot100——翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1:
image.png

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

输出:[4,7,2,9,6,3,1]

示例 2:

image.png

输入:root = [2,1,3]

输出:[2,3,1]

示例 3:

输入:root = []

输出:[]

提示:

树中节点数目范围在 [0, 100] 内

-100 <= Node.val <= 100

解法

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 func invertTree(root *TreeNode) *TreeNode {
    // 1. 基线条件
    if root == nil {
        return nil
    }
    // 2. 交换左右子树(当前层的处理)
    root.Left, root.Right = root.Right, root.Left
    // 3. 递归处理子问题
    invertTree(root.Left)
    invertTree(root.Right)
    // 4. 返回结果(原根节点已修改,直接返回)
    return root
}
comments如果有不同意见或者补充,直接留在这里。
contact

在别处继续找到我

如果你想聊技术、设计,或者只是打个招呼。

暂未配置外部链接