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.

分析:本题题意是给出两个二叉树,要求写出一个函数检查这两个二叉树从结构上和节点值是否相等。

代码实现:

/**
 * 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 p == q; }
        //结构不同
        else if (p == NULL || q == NULL) { return false; }
        //如果二叉树节点对应的值不同,则这两棵树不相等
        else if (p->val != q->val) { return false; }
        return isSameTree(p->left, q->left) 
                && isSameTree(p->right, q->right);
    }
};

你可能感兴趣的:(习题练习,leetcode练习题,学习笔记,数据结构)