package com.example.lettcode.dailyexercises;
/**
* @Class InvertTree
* @Description 226
* 翻转一棵二叉树。
* <p>
* 示例:
* 输入:
* **** 4
* ** /
* ** 2 7
* * / /
* *1 3 6 9
* <p>
* 输出:
* * 4
* * /
* * 7 2
* * / /
* 9 6 3 1
* @Author
* @Date 2020/9/16
**/
public class InvertTree {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static TreeNode invertTree(TreeNode root) {
if (root == null) return root;
dfs(root);
return root;
}
public static TreeNode dfs(TreeNode root) {
if (root == null) return root;
TreeNode rightTreeNode = dfs(root.right);
TreeNode leftTreeNode = dfs(root.left);
root.left = rightTreeNode;
root.right = leftTreeNode;
return root;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(4);
TreeNode treeNode1 = new TreeNode(2);
TreeNode treeNode2 = new TreeNode(7);
root.left = treeNode1;
root.right = treeNode2;
TreeNode treeNode3 = new TreeNode(1);
TreeNode treeNode4 = new TreeNode(3);
treeNode1.left = treeNode3;
treeNode1.right = treeNode4;
TreeNode treeNode5 = new TreeNode(6);
TreeNode treeNode6 = new TreeNode(9);
treeNode2.left = treeNode5;
treeNode2.right = treeNode6;
TreeNode treeNode = invertTree(root);
System.out.println(treeNode);
}
}