题目来源


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         

 

相关文章:

  • 2021-09-02
  • 2021-05-20
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
猜你喜欢
  • 2021-08-02
  • 2021-09-13
  • 2022-01-05
  • 2021-09-10
  • 2021-08-18
  • 2022-03-09
  • 2021-09-04
相关资源
相似解决方案