LeetCode-226. 翻转二叉树 + 镜像二叉树 + 递归

题目来源

LeetCode_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

题解分析

解法一:后序遍历

  1. 仔细观察这两颗镜像二叉树,它们的左右子树也分别是一颗镜像二叉树。
  2. 我们可以利用后序遍历来分别翻转左右子树,最后,我们需要交换root节点的左右子树。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        reverse(root);
        return root;
    }
    public void reverse(TreeNode root){
        if(root == null)
            return;
        reverse(root.left);
        reverse(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }
}
posted @ 2021-03-25 16:11  Garrett_Wale  阅读(78)  评论(0编辑  收藏  举报