Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1080 from xiaofei-2020/tree13
Browse files Browse the repository at this point in the history
添加(0257.二叉树的所有路径.md):增加typescript版本
  • Loading branch information
youngyangyang04 authored Feb 26, 2022
2 parents 1a32553 + 1b7c86e commit 83a9d8f
Showing 1 changed file with 61 additions and 6 deletions.
67 changes: 61 additions & 6 deletions problems/0257.二叉树的所有路径.md
Original file line number Diff line number Diff line change
Expand Up @@ -433,9 +433,9 @@ class Solution:
if cur.right:
self.traversal(cur.right, path + '->', result)
```

迭代法:

```python3
from collections import deque

Expand Down Expand Up @@ -463,13 +463,13 @@ class Solution:

return result
```

---

Go:

递归法:

```go
func binaryTreePaths(root *TreeNode) []string {
res := make([]string, 0)
Expand All @@ -492,7 +492,7 @@ func binaryTreePaths(root *TreeNode) []string {
return res
}
```

迭代法:

```go
Expand Down Expand Up @@ -581,7 +581,62 @@ var binaryTreePaths = function(root) {
};
```

TypeScript:

> 递归法

```typescript
function binaryTreePaths(root: TreeNode | null): string[] {
function recur(node: TreeNode, route: string, resArr: string[]): void {
route += String(node.val);
if (node.left === null && node.right === null) {
resArr.push(route);
return;
}
if (node.left !== null) recur(node.left, route + '->', resArr);
if (node.right !== null) recur(node.right, route + '->', resArr);
}
const resArr: string[] = [];
if (root === null) return resArr;
recur(root, '', resArr);
return resArr;
};
```
> 迭代法
```typescript
// 迭代法2
function binaryTreePaths(root: TreeNode | null): string[] {
let helperStack: TreeNode[] = [];
let tempNode: TreeNode;
let routeArr: string[] = [];
let resArr: string[] = [];
if (root !== null) {
helperStack.push(root);
routeArr.push(String(root.val));
};
while (helperStack.length > 0) {
tempNode = helperStack.pop()!;
let route: string = routeArr.pop()!; // tempNode 对应的路径
if (tempNode.left === null && tempNode.right === null) {
resArr.push(route);
}
if (tempNode.right !== null) {
helperStack.push(tempNode.right);
routeArr.push(route + '->' + tempNode.right.val); // tempNode.right 对应的路径
}
if (tempNode.left !== null) {
helperStack.push(tempNode.left);
routeArr.push(route + '->' + tempNode.left.val); // tempNode.left 对应的路径
}
}
return resArr;
};
```

Swift:

> 递归/回溯
```swift
func binaryTreePaths(_ root: TreeNode?) -> [String] {
Expand Down

0 comments on commit 83a9d8f

Please sign in to comment.