原文题目:
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.
读题:
给定两个二叉树,判断二叉树是否相等,判断条件是二叉树的结构一样并且各个节点的value也一样
解题思路:
有两个方法,递归和非递归,递归是采用DFS方法遍历二叉树,对每个节点和左右子树进行判断;非递归方法可以采用栈或者队列存储两棵树进行逐一比较
# 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 and q: mid = p.val == q.val l = self.isSameTree(p.left, q.left) r = self.isSameTree(p.right, q.right) return mid and l and r return p == q '''非递归''' class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ stack = [(p, q)] while stack: p, q = stack.pop() if not p and not q: continue if not p or not q: return False if p.val == q.val: stack.append((p.right, q.right)) stack.append((p.left, q.left)) else: return False return True