Skip to content

Commit

Permalink
feat: add tree iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
qiugu committed Oct 31, 2023
1 parent a8bc29c commit 3b4cde2
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions docs/tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,77 @@

因为树的特殊结构就是一个标准的递归结构,因此一般深度优先遍历都是使用递归。递归的特点:首先要有退出条件,另外就是自己调用自己,可以想象成自底向上的过程,退出条件就是base case,从这个case开始逐渐向上计算,得到最终的结果。

### 中序遍历(左根右)

递归方法:

```js
var inorderTraversal = function(root) {
const res = [];
const inorder = node => {
if (!node) return;
inorder(node.left);
res.push(node.val);
inorder(node.right);
};

inorder(root);
return res;
};
```

迭代方法:

```js
var inorderTraversal = function(root) {
const res = [];
const stack = [];
while (root || stack.length) {
while (root) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.push(root.val);
root = root.right;
}
return res;
};
```

## 二叉树的最大深度

递归方法:

```js
var maxDepth = function(root) {
// 递归退出条件
if (!root) return 0;
// 二叉树的最大深度,就是二叉树的左右子树的深度的较大值+1
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
```

迭代方法:层序遍历每一层,每遍历一层,深度+1

```js
var maxDepth = function(root) {
if (!root) return 0;
const queue = [root];
let res = 0;
while (queue.length) {
const n = queue.length;
for (let i = 0; i < n; i++) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
res++;
}
return res;
};
```

## 字典树(Trie树)

```js
Expand Down

0 comments on commit 3b4cde2

Please sign in to comment.