leetcode Same Tree

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.


解题方法:

判断两颗二叉树是否相等,第一部判断两颗二叉树是否都为空,如果都为空,则return true,如果一个为空一个不为空则return false。第二部两棵树都不为空,比较其元素,若不相等则return false。第三部,如果相等,则比较其左子树,若其左子树不相等,返回false,若相等则比较其右子树,结果return 其右子树是否为空。

代码详情:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == NULL && q == NULL) {
            return true;
        } else if (p == NULL && q != NULL) {
            return false;
        } else if (p != NULL && q == NULL) {
            return false;
        } else {
           if (p->val != q->val) {
               return false;
           } else{
               if (!isSameTree(p->left, q->left)) {
                   return false;
               } else {
                   return isSameTree(p->right, q->right);
               }
           }
        }
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_40085482/article/details/78410266