100 Same Tree

目录

原题描述

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.

分析

提供两棵树的根节点,比较两棵树是否相等,即要求结构相同且对应节点值相等。这题与求树的最大深度类似,利用递归将树不断分解转化为单个节点的比较。对于一个节点来说,有3种情况:空节点,非叶子结点,叶子节点。
现在有两棵树,组合起来则是9种情况。经过分析,可将这9种情况实际分成4种:
1.两节点中存在空节点,此时只有两个节点都为空节点时才是相等的
2.两节点都是非叶子结点,此时只有两节点的值相等且对应子树相等时才是相等的
3.两节点都是叶子节点,此时只要两节点值相等就是相等的
4.其他情况都不相等

代码示例

/**
 * 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 isParent(TreeNode* p)
    {
        if (p == NULL)
            return false;
        else
            return p->left != NULL || p->right != NULL;
    }
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == NULL || q == NULL)
            return p == NULL && q == NULL;
        else if (isParent(p) && isParent(q))
            return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        else if (!isParent(p) && !isParent(q))
            return p->val == q->val;
        else 
            return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值