[LeetCode] #226 翻转二叉树

翻转一棵二叉树。

前序遍历

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

中序遍历

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

后序遍历

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

层次遍历

class Solution {
        public TreeNode invertTree(TreeNode root) {
            if (root == null) return null;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()){
                TreeNode node = queue.poll();
                TreeNode rightTree = node.right;
                node.right = node.left;
                node.left = rightTree;
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            return root;
        }
    }

知识点:

总结:

 

posted @ 2021-09-12 13:07  1243741754  阅读(18)  评论(0编辑  收藏  举报