【LeetCode】100. 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.

提示:

此题算是一种DFS的应用。

代码:

/**
 * 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) {
        // 如果p和q都是NULL,返回真
        if (!p && !q) return true;
        // 如果p和q一个是NULL,另一个不是,则返回假
        if (p && !q || !p && q) return false;
        // 剩下最后一种都不是NULL的情况,比较他们的数据
        if (p -> val != q->val) return false;
        // 对p和q的左右两个子节点进行递归
        return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
    }
};
原文地址:https://www.cnblogs.com/jdneo/p/4738701.html