题目描述:输入两颗二叉树A,B,判断B是不是A的子结构。
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