• LeetCode:Same Tree


    问题描写叙述:

    Given two binary trees, write a function to check if they are equal or not.

    Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

    解题思路:先推断当前根节点是否同样。

    假设都为空,则直接返回true。假设当前根节不为空且存储的值同样,则递归地推断左子树和右子树是否同样。

    其它情况返回false。

    代码:

    bool isSameTree(TreeNode *p,TreeNode *q)
    {
        if(p == NULL && q == NULL)
            return true;
        if(p == NULL && q != NULL)
            return false;
        if(p != NULL && q == NULL)
            return false;
        if(p->val != q->val)
            return false;
        else
        {
            bool isLeftSubtreeSame;
            bool isRightSubtreeSame;
            isLeftSubtreeSame = isSameTree(p->left,q->left);
            isRightSubtreeSame = isSameTree(p->right,q->right);
            if(isLeftSubtreeSame && isRightSubtreeSame)
                return true;
            else
                return false;
        }
    }



  • 相关阅读:
    放缩ImageView
    2017/5/3 afternoon
    2017/5/3 morning
    2017/5/2 afternoon
    2017/5/2 morning
    2017/4/28 afternoon
    2017/4/28 morning
    2017/4/27 afternoon
    2017/4/27 morning
    2017/4/26 afternoon
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5175598.html
Copyright © 2020-2023  润新知