Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
- 先转换root ,递归转换左右子树——混起来两句实现
递归返回的是两个节点 把这两个节点转换了,注意,要设置一个tmp ,不然递归里面的 节点标志指向错误- 可以先写子树的递归,发现root.left更改过了 需要一个tmp
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
TreeNode tmp=root.left;
root.left=invertTree(root.right);
root.right=invertTree(tmp);
return root;
}
}