100. 相同的树
发布时间:2020-12-14 04:22:16 所属栏目:大数据 来源:网络整理
导读:Given two binary trees,write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / / 2 3 2 3 [1,2,3],[1,3]O
Given two binary trees,write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / / 2 3 2 3 [1,2,3],[1,3] Output: true Example 2: Input: 1 1 / 2 2 [1,2],null,2] Output: false Example 3: Input: 1 1 / / 2 1 1 2 [1,1],1,2] Output: false 给定两个二叉树,编写一个函数来检验它们是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例?1: 输入: 1 1 / / 2 3 2 3 [1,3] 输出: true 示例 2: 输入: 1 1 / 2 2 [1,2] 输出: false 示例?3: 输入: 1 1 / / 2 1 1 2 [1,2] 输出: false 1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func isSameTree(_ p: TreeNode?,_ q: TreeNode?) -> Bool { 16 //递归 17 if let p = p,let q = q 18 { 19 return p.val == q.val && isSameTree(p.left,q.left) 20 && isSameTree(p.right,q.right) 21 } 22 else 23 { 24 return p == nil && q == nil 25 } 26 } 27 } 版本:8ms 1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func isSameTree(_ p: TreeNode?,_ q: TreeNode?) -> Bool { 16 if p == nil && q == nil { 17 return true 18 } 19 if (p == nil && q != nil) || (p != nil && q == nil) { 20 return false 21 } 22 if p!.val == q!.val { 23 return isSameTree(p!.left,q!.left) && isSameTree(p!.right,q!.right) 24 } 25 return false 26 } 27 } /** * Definition for a binary tree node. * 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 == nil && q == nil { return true } else if let p = p,let q = q,p.val == q.val { return isSameTree(p.left,q.left) && isSameTree(p.right,q.right) } return false } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |