1
class Solution {
public TreeNode invertTree(TreeNode root) {
swap(root,null);
return root;
}
public void swap(TreeNode root,TreeNode parent){
if(root == null || (root.left==null && root.right==null)){
return;
}
if(root.left!=null ){
swap(root.left,parent);
}
if(root.right!=null){
swap(root.right,parent);
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
2
class Solution {
public TreeNode invertTree(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
daoxu(root,list);
TreeNode temp = new TreeNode(list.get(0));
for(int i=1;i<list.size();i++){
add(temp,list.get(i));
}
return temp;
}
public void daoxu(TreeNode root,ArrayList<Integer> list){
list.add(root.val);
if(root.right!=null){
daoxu(root.right,list);
}
if(root.left!=null){
daoxu(root.left,list);
}
}
public void add(TreeNode root,int key){
if(root == null){
root = new TreeNode(key);
return;
}
if(key > root.val){
if(root.left!=null){
add(root.left,key);
}else{
root.left = new TreeNode(key);
}
}
if(key < root.val){
if(root.right!=null){
add(root.right,key);
}else{
root.right = new TreeNode(key);
}
}
}
}
第二种 leetCode 通过不了 不知道为什么