题目:https://leetcode-cn.com/problems/invert-binary-tree/
代码:
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root != null) {
//交换
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//递归子树
this.invertTree(root.left);
this.invertTree(root.right);
}
return root;
}
}
看到二叉树就感到很复杂的样子,其实很简单。就是普通的2个变量值互换(左右子节点互换值),然后再递归子树即可。