leetCode刷题——Same Tree

来源:互联网 发布:淘宝店铺装修毕业设计 编辑:程序博客网 时间:2024/06/07 23:26

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.

题意为:判断两棵二叉树是否一样。

C代码实现accepted。思路:暴力比较,代码个人觉得写的不够简洁。先比较根节点,然后左右子树。

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

0 0
原创粉丝点击