【题目描述】
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
https://leetcode.cn/problems/invert-binary-tree/
【示例】
只要把每一个节点的左右孩子翻转一下,就可以达到整体翻转的效果(前序遍历和后序遍历都可以)
package com.company;
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;
invertTree(root.left);
invertTree(root.right);
swap(root);
return root;
}
private void swap(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}