100-Same Tree

来源:互联网 发布:什么叫国内数据流量 编辑:程序博客网 时间:2024/05/21 12:39
题目

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.

分析

两个树相等,判断条件是
1. 两个树的结构相同
2. 每个结点上的数字相同

实现
class Solution {public:    bool isSameTree(TreeNode* p, TreeNode* q) {        // 若两节点都为空,返回True        if(p == NULL&& q ==NULL)            return true;        // 若两节点仅有一结点为空,返回False        else if(p==NULL ||q == NULL)            return false;            //若两节点不为空        else            return  (p->val == q->val)&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);    }};

参考代码

bool isSameTree(TreeNode *p, TreeNode *q) {    if (p == NULL || q == NULL) return (p == q);    return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));}
原创粉丝点击