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;
    }
}
posted @ 2020-04-28 13:57  AAAmsl  阅读(65)  评论(0编辑  收藏  举报