原題
檢查兩棵二叉樹是否等價。等價的意思是說椰棘,首先兩棵二叉樹必須擁有相同的結(jié)構(gòu)懒浮,并且每個對應(yīng)位置上的節(jié)點(diǎn)上的數(shù)都相等。
樣例
1 1
/ \ / \
2 2 and 2 2
/ /
4 4
就是兩棵等價的二叉樹识藤。
1 1
/ \ / \
2 3 and 2 3
/ \
4 4
就不是等價的砚著。
解題思路
- 如果兩棵樹都是None,認(rèn)為是等價的
- Recursion - 遞歸求解痴昧,分治的思路稽穆,如果
a.val == b.val
,則只需考慮左右子樹是不是Identical Binary Tree
完整代碼
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param a, b, the root of binary trees.
@return true if they are identical, or false.
"""
def isIdentical(self, a, b):
# Write your code here
if a is None and b is None:
return True
if a and b and a.val == b.val:
return self.isIdentical(a.left, b.left) and self.isIdentical(a.right, b.right)
return False