leetcode : same-tree:判断是不是相同的树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Qiana_/article/details/81805516

题目描述:

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.

题目解析:

两个二叉树是相同的树,包括它们的结构是相同的并且它们的节点的值是相同的。

采用递归来进行判断,不断的递归左子树和右子树,如果其中有一个值不一样或者结构不一样,就返回false。

/**
 * Definition for binary tree
 * 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;
        if(p == NULL || q == NULL)
            return false;
        if(p->val != q->val)
            return false;
        return (isSameTree(p->left,q->left) && isSameTree(p->right,q->right));
    }
};

(*^▽^*)

猜你喜欢

转载自blog.csdn.net/Qiana_/article/details/81805516