美文网首页
二叉树的镜像

二叉树的镜像

作者: 我的天气很好啦 | 来源:发表于2018-10-12 09:41 被阅读0次

    🍞环境:牛客的编译环境
    🍰语言:JavaScript
    ☕️难点:一开始想不出来怎么去交换子树..后来思考了几分钟想出来了
    🍊题目:操作给定的二叉树,将其变换为源二叉树的镜像。
    输入描述:
    二叉树的镜像定义:源二叉树
    8
    /
    6 10
    / \ /
    5 7 9 11
    镜像二叉树
    8
    /
    10 6
    / \ /
    11 9 7 5
    🍎思路:利用后序遍历,找到最后一个节点后,判断该节点有无子节点,若有,则交换子节点,若无,则不做处理。
    🍇我的代码:

    /* function TreeNode(x) {
        this.val = x;
        this.left = null;
        this.right = null;
    } */
    function preOrder(root){
        if(root.left)
            preOrder(root.left);
        if(root.right)
            preOrder(root.right);
        if(root.left || root.right){
            var tmp = root.right;
            root.right = root.left;
            root.left = tmp;
        }
    }
    function Mirror(root)
    {
        // write code here
        if(root == null)
            return null;
        else{
            preOrder(root);
            return root;
        }
    }
    

    🥒大佬的精简代码:

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
        void Mirror(TreeNode *pRoot) {
            if(pRoot==NULL){
                return;
            }
            TreeNode *tmp = pRoot->left;
            pRoot->left = pRoot->right;
            pRoot->right = tmp;
            Mirror(pRoot->left);
            Mirror(pRoot->right);
        }
    };
    

    相关文章

      网友评论

          本文标题:二叉树的镜像

          本文链接:https://www.haomeiwen.com/subject/brswaftx.html