• LeetCode 226: Invert Binary Tree


    /**
     * 226. Invert Binary Tree
     * 1. Time:O(n)  Space:O(n)
     * 2. Time:O(n)  Space:O(n)
     */
    
    // 1. Time:O(n)  Space:O(n)
    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root==null) return null;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()){
                TreeNode cur = queue.poll();
                TreeNode tmp = cur.left;
                cur.left = cur.right;
                cur.right = tmp;
                if(cur.left!=null) queue.add(cur.left);
                if(cur.right!=null) queue.add(cur.right);
            }
            return root;
        }
    }
    
    // 2. Time:O(n)  Space:O(n)
    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;
        }
    }
    
  • 相关阅读:
    Arr
    class4
    class3联大网页
    class33
    class3
    人机交换 NO 1书签
    大数据的框架与特点
    mapreduce排序
    mapreduce求平均数
    mapreduce去重
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12793781.html
Copyright © 2020-2023  润新知