剑指offer13 JZ27 二叉树的镜像

二叉树的镜像

https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7?tpId=13&tqId=1374963&ru=%2Fpractice%2F6e196c44c7004d15b1610b9afca8bd88&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13

递归

alt

  1. 使用前序遍历
  2. 只要左子树或者右子树有一个不为空就可以交换
  3. 最后返回根节点就可以
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) {
        // write code here
        
        if(pRoot==null){
            return null;
        }
        TreeNode temp;
        //只要有一个不为空就可以交换
        if(pRoot.left!=null || pRoot.right!=null){//判断左子树与右子树是否为空
            temp=pRoot.left;
            pRoot.left=pRoot.right;
            pRoot.right=temp; //交换
        }
        Mirror(pRoot.left);
        Mirror(pRoot.right);
        return pRoot;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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