# 无法找出遍历的逻辑缺陷以检查树中是否有特定的子树

``````Given tree s:
3
/ \
4   5
/ \
1   2

Given tree t:
4
/ \
1   2
``````

``````Given tree s:
3
/ \
4   5
/ \
1   2
/
0

Given tree t:
4
/ \
1   2
``````

``````class TreeNode {
constructor(val, left, right) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}

const isSubtree = (s, t) => {
if (!s || !t) return false
let sameTree = false

const isSubtree = (s, t) => {
if (!s || !t) return false
let sameTree = false

//changed to preOrder, but it does not work for left or right skewed trees
const dfsPO = c => {
if (!c) return
if (c.val === t.val) sameTree = isSameTree(c, t)
if (c.left) dfsPO(c.left)
if (c.right) dfsPO(c.right)
return sameTree
}
return sameTree = dfsPO(s)
}

const isSameTree = (c, t) => {
if (!c && !t) return true
if (!c || !t) return false
if (c.val !== t.val) return false
return isSameTree(c.left, t.left) && isSameTree(c.right, t.right)
}
``````

``````const tree1 = new TreeNode(3, new TreeNode(4, new TreeNode(1), new TreeNode(2)), new TreeNode(5))
const tree2 = new TreeNode(4, new TreeNode(1), new TreeNode(2))

const tree3 = new TreeNode(3, new TreeNode(4, new TreeNode(1), new TreeNode(2, new TreeNode(0))), new TreeNode(5))
const tree4 = new TreeNode(4, new TreeNode(1), new TreeNode(2))

const tree5 = new TreeNode(1, new TreeNode(1))
const tree6 = new TreeNode(1)

console.log(isSubtree(tree1, tree2)) //true
console.log(isSubtree(tree3, tree4)) //false
console.log(isSubtree(tree5, tree6)) //true

//the input for the tree that fails is as follows:

//[1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,2]
//[1,null,1,null,1,null,1,null,1,null,1,2]
``````