给你一棵二叉树的根节点 root,翻转这棵二叉树,并返回其根节点

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(){}
    TreeNode(int val){
        this.val = val;
    }
    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/*
递归的进行翻转
保存原来的右子树
 */
public class Solution1 {
    public TreeNode invertTree(TreeNode root){
        if(root == null){
            return null;
        }
        //保存右子树
        TreeNode rightTree = root.right;
        root.left = invertTree(root.right);
        root.right = invertTree(root.left);
        return root;
    }
}


import java.util.LinkedList;
import java.util.Queue;

//层序遍历,使用队列
public class Solution2 {
    public TreeNode invertTree(TreeNode root){
        if(root == null){
            return null;
        }
        Queue stack = new LinkedList<>();
        stack.offer(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.poll();
            //保存右子树结点
            TreeNode rightTree = node.right;
            node.right = node.left;
            node.left = rightTree;
            if(node.left != null){
                stack.offer(node.left);
            }
            if(node.right != null){
                stack.offer(node.right);
            }
        }
        return root;
    }
}

public class Solution3 {
    public TreeNode invertTree(TreeNode root){
        if(root == null){
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.right = left;
        root.left = right;
        return root;
    }
}

你可能感兴趣的:(算法)