JZ18-二叉树的镜像

二叉树的镜像

https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

class Solution {
    //递归
    public void Mirror(TreeNode pRoot) {
        if (pRoot == null) {
            return;
        }

        Mirror(pRoot.left);
        Mirror(pRoot.right);

        TreeNode temp = pRoot.left;
        pRoot.left = pRoot.right;
        pRoot.right = temp;
    }

    //
    public void Mirror2(TreeNode pRoot) {
        if (pRoot == null) {
            return;
        }

        Stack<TreeNode> stack = new Stack<>();

        stack.push(pRoot);

        while (!stack.isEmpty()) {
            TreeNode tempRoot = stack.pop();

            if (tempRoot == null) {
                continue;  //无需交换
            }
            if (tempRoot.left == null && tempRoot.right == null) {
                continue;  //无需交换
            }

            TreeNode temp = tempRoot.left;
            tempRoot.left = tempRoot.right;
            tempRoot.right = temp;

            stack.push(tempRoot.right);  //在此题可以随便换位置,但是在Dfs中,只能先右后左
            stack.push(tempRoot.left);
        }
    }
}

全部评论

相关推荐

05-30 13:04
已编辑
门头沟学院 算法工程师
智谱和米哈游都是ai大模型agent的业务钱的话还是米更多,几乎翻倍了,有没有老哥是两个公司其中一个的,能问问转正率咋样嘛,我问的hr回答都是做的好就可以转正暑期实习
码农索隆:选米哈游:短期高薪、敢承担风险、具备强创新能力,且愿押注游戏AI赛道。 选智谱:稳定性与行业通用能力积累,接受薪资差距以换取更稳妥的职业基础。
投递北京智谱华章科技等公司10个岗位 > 实习期间如何提升留用概率?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务