226. 翻转二叉树

深度优先搜索

class Solution {
    public TreeNode invertTree(TreeNode root) {

        if (root == null){
            return null;
        }
        
        /**
         * 后序遍历
         */
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        
        root.left = right;
        root.right = left;
        
        return root;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

迭代

class Solution {
    public TreeNode invertTree(TreeNode root) {

        if (root == null){
            return root;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while (!stack.isEmpty()){
            
            /**
             * 前序遍历
             */
            TreeNode temp = stack.pop();
            TreeNode swap = temp.left;
            temp.left = temp.right;
            temp.right = swap;
            
            if (temp.left != null){
                stack.push(temp.left);
            }
            
            if (temp.right != null){
                stack.push(temp.right);
            }
        }

        return root;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

广度优先搜索

class Solution {
    public TreeNode invertTree(TreeNode root) {

        if (root == null){
            return root;
        }

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);

        /**
         * 层序遍历
         */
        while (!queue.isEmpty()){

            int size = queue.size();

            for (int i = 0; i < size; i++) {

                TreeNode temp = queue.poll();
                TreeNode swap = temp.left;
                temp.left = temp.right;
                temp.right = swap;
                
                if (temp.left != null){
                    queue.add(temp.left);
                }
                
                if (temp.right != null){
                    queue.add(temp.right);
                }
            }
        }
        
        return root;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/invert-binary-tree/

posted @ 2021-10-28 10:44  振袖秋枫问红叶  阅读(27)  评论(0)    收藏  举报