介绍
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例1:
输入:root=[4, 2, 7, 1, 3, 6, 9]
输出:[4, 7, 2, 9, 6, 3, 1]
题解
Java
//定义二叉树节点
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 {
public TreeNode invertTree(TreeNode root) {
//当前层级递归函数的终止条件,节点为空时返回
if(root==null) {
return null;
}
//将当前节点的左右子树交换
TreeNode tmp = root.right;
root.right = root.left;
root.left = tmp;
//递归交换当前节点的左子树
invertTree(root.left);
//递归交换当前节点的右子树
invertTree(root.right);
//当前节点及其子节点都交换完成
return root;
}
}