【算法】二叉树的镜像

【算法】二叉树的镜像

https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7?tpId=188&tqId=38075&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high-week%2Fquestion-ranking&tab=answerKey


1.题目

1615605600132


2.推荐解析

  • 代码

    二叉树中很重要的递归思想

    import java.util.*;
    
    /*
     * public class TreeNode {
     *   int val = 0;
     *   TreeNode left = null;
     *   TreeNode right = null;
     *   public TreeNode(int val) {
     *     this.val = val;
     *   }
     * }
     */
    
    /**
     * @title 二叉树的镜像
     * @description 使用递归的思想:
     * 交换当前节点左右子节点,再递归左右子节点进行相同操作
     * @author musecho801
     * @date 2021/3/13 10:58
     */
    public class Solution {
    
        public TreeNode Mirror (TreeNode pRoot) {
            if(pRoot==null) return null;
            
            TreeNode temp=pRoot.left;
            pRoot.left=pRoot.right;
            pRoot.right=temp;
            
            Mirror(pRoot.left);
            Mirror(pRoot.right);
            
            return pRoot;
        }
    }
    
posted @ 2021-03-13 11:21  musecho  阅读(80)  评论(0)    收藏  举报