Skip to content

Commit

Permalink
添加(0104.二叉树的最大深度.md):增加typescript版本
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaofei-2020 committed Jan 31, 2022
1 parent 97bc7ef commit 46571a3
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions problems/0104.二叉树的最大深度.md
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,55 @@ var maxDepth = function(root) {
};
```

## TypeScript:

> 二叉树的最大深度:

```typescript
// 后续遍历(自下而上)
function maxDepth(root: TreeNode | null): number {
if (root === null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};

// 前序遍历(自上而下)
function maxDepth(root: TreeNode | null): number {
function recur(node: TreeNode | null, count: number) {
if (node === null) {
resMax = resMax > count ? resMax : count;
return;
}
recur(node.left, count + 1);
recur(node.right, count + 1);
}
let resMax: number = 0;
let count: number = 0;
recur(root, count);
return resMax;
};

// 层序遍历(迭代法)
function maxDepth(root: TreeNode | null): number {
let helperQueue: TreeNode[] = [];
let resDepth: number = 0;
let tempNode: TreeNode;
if (root !== null) helperQueue.push(root);
while (helperQueue.length > 0) {
resDepth++;
for (let i = 0, length = helperQueue.length; i < length; i++) {
tempNode = helperQueue.shift()!;
if (tempNode.left) helperQueue.push(tempNode.left);
if (tempNode.right) helperQueue.push(tempNode.right);
}
}
return resDepth;
};
```
## C
二叉树最大深度递归
```c
int maxDepth(struct TreeNode* root){
Expand Down

0 comments on commit 46571a3

Please sign in to comment.