cubegao

Swift.树的子结构

2015-07-10

题目描述:输入两颗二叉树A,B,判断B是不是A的子结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Foundation

class For18Solution {
func isSubTreeNode(_ pRoot: TreeNode?,_ qRoot: TreeNode?) -> Bool {

var res = false

if pRoot != nil && qRoot != nil {
if pRoot?.val == qRoot?.val {
res = runSubTreeNode(pRoot, qRoot)
}

if !res {
res = isSubTreeNode(pRoot?.left, qRoot)
}

if !res {
res = isSubTreeNode(pRoot?.right, qRoot)
}
}

return res

}

func runSubTreeNode(_ pRoot: TreeNode?,_ qRoot: TreeNode?) -> Bool {

if qRoot == nil {
return true
}

if pRoot == nil {
return false
}

if pRoot?.val != qRoot?.val {
return false
}

return runSubTreeNode(pRoot?.left,qRoot?.left)&&runSubTreeNode(pRoot?.right,qRoot?.right)
}
}

算法思想:遍历到最后,节点为空那就是子结构,相反不是。

github地址:https://github.com/cubegao/LeetCode

Tags: 算法

扫描二维码,分享此文章