Article directory
tree substructure
Input two binary trees A and B, and judge whether B is a substructure of A. (It is agreed that an empty tree is not a substructure of any tree)
B is a substructure of A, that is, A has the same structure and node value as B.
topic
train of thought
dfs(A, B) function:
Termination condition:
when node B is empty: it means that tree B has been matched (passing the leaf node), so it returns true;
when node A is empty: it means that the tree A leaf node has been crossed, that is, the matching fails , return false;
when the values of nodes A and B are different: it means that the matching fails, return false;
return value:
judge whether the left child nodes of AA and BB are equal, that is, recur(A.left, B.left);
judge AA and BB Whether the right sub-nodes are equal, that is, recur(A.right, B.right);
isSubStructure(A, B) function:
special case processing: when tree A is empty or tree B is empty, return false directly;
return value: if Tree B is a substructure of tree A, and it must satisfy one of the following three conditions, so use || to connect; the
subtree with node AA as the root node contains tree BB, corresponding to dfs(A, B);
tree B is The substructure of the left subtree of tree A corresponds to isSubStructure(A.left, B); the
substructure of tree B is the right subtree of tree A, corresponding to isSubStructure(A.right, B)
the code
var isSubStructure = function (A, B) {
if (A===null||B===null) return false;
return dfs(A,B)||isSubStructure(A.left, B)||isSubStructure(A.right, B);
};
function dfs(A,B) {
if (B==null) return true;
if (A==null) return false;
return A.val===B.val&&dfs(A.left, B.left)&&dfs(A.right, B.right);
}
binary tree mirroring
Please complete a function that takes as input a binary tree and the function outputs its mirror image.
topic
train of thought
Swap the left and right nodes of the binary tree
the code
var mirrorTree = function(root) {
if(root == null){
return null
}
[[root.left,root.right]] = [[root.right,root.left]]
mirrorTree(root.left)
mirrorTree(root.right)
return root
};
Symmetrical Binary Tree
Please implement a function to judge whether a binary tree is symmetric. A binary tree is symmetric if it is the same as its mirror image.
topic
train of thought
Directly compare its left and right nodes
the code
var isSymmetric = root => {
return isSymmetricCore(root, root)
}
var isSymmetricCore = (n1, n2) => {
// 两个空结点
if (!n1&&!n2) return true
// 一个为空,一个不为空
if (!n1||!n2) return false
if (n1.val!==n2.val) return false
return isSymmetricCore(n1.left, n2.right) && isSymmetricCore(n1.right, n2.left)
}