[LeetCode]题解(python):100 Same Tree

Posted loadofleaf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):100 Same Tree相关的知识,希望对你有一定的参考价值。

题目来源


https://leetcode.com/problems/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.


题意分析


Input: twon binary tree

Output: equal?

Conditions:判断两个二叉树是不是相等。


题目思路


逐一遍历,看是否相等。


AC代码(Python)

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def isSameTree(self, p, q):
10         """
11         :type p: TreeNode
12         :type q: TreeNode
13         :rtype: bool
14         """
15         def dfs(p, q):
16             if p == None and q != None:
17                 return False
18             if p != None and q == None:
19                 return False
20             if p == None and q == None:
21                 return True
22             if p.val != q.val:
23                 return False
24             return dfs(p.left, q.left) and dfs(p.right, q.right)
25         
26         return dfs(p,q)
27         

 

以上是关于[LeetCode]题解(python):100 Same Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 热题 HOT 100 完整题解笔记&知识点分类 C++代码实现

七万字❤️零基础学算法 LeetCode 热题 HOT 100(附题解,强烈建议收藏)

[LeetCode]题解(python):112 Path Sum

[LeetCode]题解(python):133-Clone Graph

[LeetCode]题解(python):101-Symmetric Tree

[LeetCode]题解(python):101 Symmetric tree