判断两个二叉树是否相等,递归思路:
先判断两个二叉树的根的值是否相同,如相同则比较他们的左子树与右子树是否相同。递归结束的条件是传入的两个二叉树都是空。
//二叉树结构类
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
//判断类
class Solution {
func isSameTree(p: TreeNode?,_ q: TreeNode?) -> Bool {
if p?.val != q?.val {
return false
}else{
if p?.val == nil && q?.val == nil {
return true
}else{
return isSameTree(p?.left,q?.left)&&isSameTree(p?.right,q?.right)
}
}
}
原文链接:https://www.f2er.com/swift/323390.html