当前位置: 代码迷 >> 综合 >> leetcode-Algorithms-226|翻转二叉树
  详细解决方案

leetcode-Algorithms-226|翻转二叉树

热度:55   发布时间:2023-12-12 11:26:31.0

原题

在这里插入图片描述

思路

DFS,递归

代码

public class Solution_226 {
    public static void main(String[] args) {
    TreeNode root = new TreeNode(4);root.left = new TreeNode(2);root.right = new TreeNode(7);root.left.left = new TreeNode(1);root.left.right = new TreeNode(3);root.right.left = new TreeNode(6);root.right.right = new TreeNode(9);invertTree(root);}public static TreeNode invertTree(TreeNode root) {
    dfs(root);return root;}private static void dfs(TreeNode root) {
    if (root == null) {
    return;}TreeNode tmp = root.left;root.left = root.right;root.right = tmp;dfs(root.left);dfs(root.right);}
}