Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
func isSubtree(_ s: TreeNode?, _ t: TreeNode?) -> Bool { return ( maxDepth(s) >= maxDepth(t) ) && ( isSameTree(s, t) || (s?.left != nil && isSubtree(s?.left, t)) || (s?.right != nil && isSubtree(s?.right, t)) ) } private func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { if let p = p, let q = q { return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) } else { return p == nil && q == nil } } private func maxDepth(_ root: TreeNode?) -> Int { return root == nil ? 0 : 1 + max(maxDepth(root?.left), maxDepth(root?.right)) } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼