NC72 二叉树的镜像(C++)- 简单、树

NC72 二叉树的镜像(C++)- 简单、树,第1张

题目链接:https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7?tpId=196&tqId=37103&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D2%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=undefined&judgeStatus=undefined&tags=&title=
题目如下:

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        if(pRoot==nullptr) return pRoot;
        
        //根左右,前序遍历
        //if(pRoot->left&&pRoot->right){//交换当前节点的左右子树
        //注:上一条语句哪怕不是完全二叉树,也可以镜像!!!
            auto temp=pRoot->left;
            pRoot->left=pRoot->right;
            pRoot->right=temp;
        //}
        
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        
        return pRoot;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1498184.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-25
下一篇2022-06-25

发表评论

登录后才能评论

评论列表(0条)

    保存