【LeetCode笔记】226. 翻转二叉树(Java、递归)

文章目录

  • 题目描述
  • 代码 & 思路
      • 更新版

题目描述

  • 感觉和合并二叉树类似,都是很好进行递归的问题
    【LeetCode笔记】226. 翻转二叉树(Java、递归)_第1张图片

代码 & 思路

  • 翻转当前结点的左、右结点
  • 对当前结点的左、右结点进行翻转函数
  • 【自底向上】
/**
 * 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 {
    TreeNode left;
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return root;
        }
        invertTree(root.left);
        invertTree(root.right);
        left = root.left;
        root.left = root.right;
        root.right = left;
        return root;
    }
}

更新版

  • 自顶向下,感觉这个比较好理解
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}
  • 面试前再刷一次,属实是过于清晰了
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) return null;
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }
}

你可能感兴趣的:(LeetCode要每天都刷噢,二叉树,算法,leetcode,java)