树的子结构
输入两棵二叉树A和B,判断B是不是A的子结构。
思路
1 在树A中找到和树B的根节点的值一样的节点R
2 判断树A中以R为根节点的子树是不是包含和树B一样的结构
代码
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} A
* @param {TreeNode} B
* @return {boolean}
*/
var isSubStructure = function(A, B) {
let result = false;
if (A !== null && B !== null) {
if (A.val === B.val) {
result = doesHasSubTree(A, B);
}
if (!result) {
result = isSubStructure(A.left, B);
}
if (!result) {
result = isSubStructure(A.right, B);
}
}
return result;
};
function doesHasSubTree(A, B) {
if (B === null) {
return true;
}
if (A === null) {
return false;
}
if (A.val !== B.val) {
return false;
}
return doesHasSubTree(A.left, B.left) && doesHasSubTree(A.right, B.right);
}
复杂度分析
- 时间复杂度: O(MN)
- 空间复杂度: O(M)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG