题解 | 二叉树的镜像

二叉树的镜像

https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        // return invertRecursively(pRoot);

        return invertIteratively(pRoot);
    }

    /**
     * 递归方式实现二叉树镜像
     *
     * @param root 二叉树的根节点
     * @return 镜像后的二叉树根节点
     */
    public TreeNode invertRecursively (TreeNode pRoot) {
        // 基本情况:如果当前节点为空,直接返回
        if (pRoot == null) return pRoot;

        // 递归处理左子树
        TreeNode leftMirror = invertRecursively(pRoot.left);
        // 递归处理右子树
        TreeNode rightMirror = invertRecursively(pRoot.right);

        // 交换左右子树
        pRoot.left = rightMirror;
        pRoot.right = leftMirror;

        return pRoot;
    }
    /**
     * 迭代方式实现二叉树镜像(使用栈)
     *
     * @param root 二叉树的根节点
     * @return 镜像后的二叉树根节点
     */
    public TreeNode invertIteratively (TreeNode pRoot) {
        // 处理空树的情况
        if (pRoot == null) return pRoot;

        // 使用栈来模拟递归过程
        Stack<TreeNode> stack = new Stack<>();
        stack.push(pRoot);

        while (!stack.isEmpty()) {
            // 获取栈顶节点并弹出
            TreeNode node = stack.pop();

            // 将左右子节点入栈(注意顺序:先左后右,因为栈是后进先出)
            if (node.left != null) {
                stack.push(node.left);
            }

            if (node.right != null) {
                stack.push(node.right);
            }

            // 交换当前节点的左右子树
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }

        return pRoot;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务