zoukankan      html  css  js  c++  java
  • 编写代码判断两棵二叉树是否为镜像二叉树 镜像二叉树举例:

    编写代码判断两棵二叉树是否为镜像二叉树
    镜像二叉树举例:

       a              a
     b   c    ==>   c   b
    d                    d

    下面是将一个树转化为镜像二叉树

    void swap(struct BiTree** a, struct BiTree** b)  //交换将左右子树交换
    {
        struct BiTree* temp = NULL;
        temp = *a;
        *a = *b;
        *b = temp;
    }

    struct BiTree* mirrorTree(struct BiTree* root)  
    {
        if (root == NULL)
        {
            return NULL;
        }

        if (root->left != NULL)  //递归到左子树最深处,
        {
            root->left = mirrorTree(root->left);  //运用递归
        }

        if (root->right != NULL)    //递归到又子树最深处
        {
            root->right = mirrorTree(root->right);//运用递归
        }

        swap(&root->left, &root->right);//  //将左右节点交换
        return root;
    }

    简洁高效的算法:

     一直递归,判断是否相等,递归完左子树再递归右子树

     易懂的算法:

    struct BiTree
    {
        int data;
        struct BiTree* left;
        struct BiTree* right;
    };

    bool isMirrorTree(struct BiTree* a, struct BiTree* b)
    {
        if (a == NULL && b == NULL)
        {
            return true;
        }

        if (a == NULL && b != NULL)
        {
            return false;
        }

        if (a != NULL && b == NULL)
        {
            return false;
        }

        if (a->data != b->data)
        {
            return false;
        }

        if (a->right != NULL)
        {
            if (b->left != NULL)
            {
                if (!isMirrorTree(a->right, b->left))
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        if (a->left != NULL)
        {
            if (b->right != NULL)
            {
                if (!isMirrorTree(a->left, b->right))
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        return true;
    }

  • 相关阅读:
    卷积神经网络入门(1) 识别猫狗
    lumen 获得当前uri 如/xxx/{id}
    React ES5 (createClass) 和 ES6 (class)
    lumen 单元测试
    mysql 高级语法手记
    react手记(componentWillMount,componentDidMount等)
    lumen 事件
    PDO drivers no value in Windows
    BindingNavigator操作DatagridView的数据
    <input type="hidden" id="haha" name="wang" value="xiaodong" />
  • 原文地址:https://www.cnblogs.com/txzing/p/13957962.html
Copyright © 2011-2022 走看看