一、今日刷题
1. 第六部分:哈希表 – 226. 翻转二叉树
答案代码:
自己的思路:模仿树节点的前中后序遍历,采用递归的方法,从 root 节点开始,交换其左右子节点,并递归地执行。
package BinaryTree;
import javax.swing.tree.TreeCellRenderer;
/**
* @author: LYZ
* @date: 2022/2/19 14:58
* @description: 226.翻转二叉树
*/
public class InvertTree {
public static void main(String[] args) {
TreeNode root = new TreeNode(1, new TreeNode(2), new TreeNode(3));
InvertTree invertTree = new InvertTree();
TreeNode ans = invertTree.invertTree(root);
System.out.println(ans);
}
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
public void invert(TreeNode root) {
if (root == null) {
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invert(root.left);
invert(root.right);
}
}