🌕 剑指 Offer 27. 二叉树的镜像

吞佛童子2022年10月10日
  • algorithm
  • Tree
小于 1 分钟

🌕 剑指 Offer 27. 二叉树的镜像

难度: 🌕

问题描述

img_25.png


解法 1 - 递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        // 思路:
        // 迭代
        mySol(root);
        return root;
    }

    private void mySol(TreeNode root) {
        // 递归终止条件
        if(root == null) {
            return;
        }
        // root != null
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.left = right;
        root.right = left;
        mySol(root.left);
        mySol(root.right);
    }
}

输出 1

img_24.png


解法 2 - 迭代

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        // 思路:
        // 迭代 - 借助栈
        if(root == null) {
            return root;
        }
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            TreeNode left = cur.left;
            TreeNode right = cur.right;
            cur.left = right;
            cur.right = left;
            if(cur.left != null) {
                stack.push(cur.left);
            } 
            if(cur.right != null) {
                stack.push(cur.right);
            }
        }
        return root;
    }
}

输出 2

img_26.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou