leetcode100题 题解 翻译 C语言版 Python版

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.

100.相同的树

给定两棵二叉树,写一个函数来检查他们是否相等

这里说的两棵二叉树相等是指他们结构完全相同并且对应的结点有相同的值。


思路:用递归可快速解决问题。当比较两棵树的对应两个结点时,如果他们的左子树完全一样,右子树完全一样,同时这两个结点的值也一样,那么就可以得到两个结点带领的树是完全一样的了。由于存在一些结点有左子树却右子树为空,或有右子树却左子树为空,这样在调用函数本身时会把NULL作为参数传下去,所以递归的终点应该是比较的两个结点指针值为空。如果两个都是空,那就视为相同,返回true。而一个为空另一个不为空就视为不同,返回false,不用往下递归了。

/**
 * Definition for a binary tree node.
 * 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->val==q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right))
        return true;
    else
        return false;
}

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p == None and q == None: return True
        if p == None or q == None: return False
        if p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right):
            return True
        else:
            return False



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值