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

时间:2023-03-10 06:24:59
[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)

 # 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
"""
def dfs(p, q):
if p == None and q != None:
return False
if p != None and q == None:
return False
if p == None and q == None:
return True
if p.val != q.val:
return False
return dfs(p.left, q.left) and dfs(p.right, q.right) return dfs(p,q)