
解题思路
- 求二叉树深度,可以使用深度优先
- 每次递归调用,传入一个 深度变量值,调用一次累加一次
var maxDepth = function(root) {
let max = 0;
const dfs = (tree, l) => {
if(!tree) { return; }
if(!tree?.left && !tree?.right) {
max = Math.max(max,l);
}
tree?.left && dfs(tree?.left,l +1)
tree?.right && dfs(tree?.right, l + 1)
}
dfs(root,1)
return max;
};

解题思路
- 求最小深度,广度优先遍历比较合适
- 只要找到同时没事没有左右节点,就是叶子节点了
var minDepth = function(root) {
const bfs = (tree) => {
if(!tree) { return 0}
const queue = [[tree,1]];
while(queue.length) {
const [n,l] = queue.shift();
if(!n?.left && !n?.right) {
return l;
}
if(n?.left) {
queue.push([n.left,l +1])
}
if(n?.right) {
queue.push([n.right, l +1]);
}
}
}
return bfs(root);
};

解题思路
class MinHeap {
constructor() {
this.heap = [];
}
_swap(i1, i2) {
const temp = this.heap[i1];
this.heap[i1] = this.heap[i2];
this.heap[i2] = temp;
}
_getLeftIndex(index) {
return index * 2 + 1;
}
_getRightIndex(index) {
return index * 2 + 2;
}
_getParentIndex(index) {
return Math.floor((index - 1) / 2);
}
_shiftDown(index) {
const leftIndex = this._getLeftIndex(index);
const rightIndex = this._getRightIndex(index);
if (this.heap[leftIndex] < this.heap[index]) {
this._swap(index, leftIndex);
this._shiftDown(leftIndex);
}
if ( this.heap[rightIndex] < this.heap[index] ) {
this._swap(index, rightIndex);
this._shiftDown(rightIndex);
}
}
_shiftUp(index) {
if (index === 0) {
return;
}
const parentIndex = this._getParentIndex(index);
if (this.heap[parentIndex] > this.heap[index] ) {
this._swap(index, parentIndex);
this._shiftUp(parentIndex);
}
}
get size() {
return this.heap.length;
}
get peek() {
return this.heap[0];
}
get heapList() {
return this.heap;
}
pop() {
this.heap[0] = this.heap.pop();
this._shiftDown(0);
}
insert(value) {
this.heap.push(value);
this._shiftUp(this.heap.length - 1);
}
}
var findKthLargest = function(nums, k) {
const h = new MinHeap();
nums.forEach(n => {
h.insert(n);
if(h.size > k) {
h.pop();
}
})
return h.peek;
};