题目:
思路:递归三部曲:参数(root) 终止条件(root == null) 单层递归逻辑(将左右孩子交换,然后不断递归左右孩子)。要注意交换左右孩子时,引用传递的问题,我一开始
java
/**
* Definition for a binary tree node.
* 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 temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
是将局部变量在交换,实际上的对象完全没有交换。