题解 | #二叉树的镜像#

二叉树的镜像

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 root) {
        // write code here
        if(root==null){
            return root;
        }
        // // TreeNode left=invertTree(root.left);
        // // TreeNode right=invertTree(root.right);
        // root.left=invertTree(root.right);
        // root.right=invertTree(root.left);//root.left 在调用 invertTree(root.right) 后已经被修改为新的右子树,再用 invertTree(root.left) 时,它实际上已经是更新后的右子树了,这样会导致子树反转的逻辑不正确。
        TreeNode left=Mirror(root.left);
        TreeNode right=Mirror(root.right);
        root.left=right;
        root.right=left;
        return root;
    }
}

全部评论

相关推荐

12-15 14:25
云南大学 Java
lei22:入职可能会看学信网,最好别伪装,这个简历找实习肯定是够的,肯定会有收 28 届实习生的公司的,多投就行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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