美文网首页
LeetCode 剑指 Offer 27. 二叉树的镜像

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

作者: 陈陈chen | 来源:发表于2021-08-24 18:59 被阅读0次

1、题目

image.png

2、分析

其实就对每一个子树做左右结点的互换就可以了,比较好理解

3、代码

递归1.0版本:

/**
 * 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 null;
        TreeNode tmp = new TreeNode();
        tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }
}

递归2.0版本:

/**
 * 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 null;
        TreeNode tmp = root.left;
        TreeNode leftRoot = mirrorTree(root.left);
        TreeNode rightRoot = mirrorTree(root.right);
        root.left = root.right;
        root.right = tmp;
        return root;
    }
}

栈的实现:

/**
 * 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 null;
        Stack<TreeNode> stack = new Stack();
        stack.add(root);
        while(!stack.empty()){
            TreeNode node = stack.pop();
            if (node.left != null) stack.add(node.left);
            if (node.right != null) stack.add(node.right);
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }
}

相关文章

网友评论

      本文标题:LeetCode 剑指 Offer 27. 二叉树的镜像

      本文链接:https://www.haomeiwen.com/subject/uoodiltx.html