mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #868 from hjwforever/patch-4
update: 0257.二叉树的所有路径, 增加go与js版本的递归解法
This commit is contained in:
@ -469,6 +469,9 @@ class Solution:
|
|||||||
---
|
---
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
递归法:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func binaryTreePaths(root *TreeNode) []string {
|
func binaryTreePaths(root *TreeNode) []string {
|
||||||
res := make([]string, 0)
|
res := make([]string, 0)
|
||||||
@ -491,10 +494,45 @@ func binaryTreePaths(root *TreeNode) []string {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
迭代法:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func binaryTreePaths(root *TreeNode) []string {
|
||||||
|
stack := []*TreeNode{}
|
||||||
|
paths := make([]string, 0)
|
||||||
|
res := make([]string, 0)
|
||||||
|
if root != nil {
|
||||||
|
stack = append(stack, root)
|
||||||
|
paths = append(paths, "")
|
||||||
|
}
|
||||||
|
for len(stack) > 0 {
|
||||||
|
l := len(stack)
|
||||||
|
node := stack[l-1]
|
||||||
|
path := paths[l-1]
|
||||||
|
stack = stack[:l-1]
|
||||||
|
paths = paths[:l-1]
|
||||||
|
if node.Left == nil && node.Right == nil {
|
||||||
|
res = append(res, path+strconv.Itoa(node.Val))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if node.Right != nil {
|
||||||
|
stack = append(stack, node.Right)
|
||||||
|
paths = append(paths, path+strconv.Itoa(node.Val)+"->")
|
||||||
|
}
|
||||||
|
if node.Left != nil {
|
||||||
|
stack = append(stack, node.Left)
|
||||||
|
paths = append(paths, path+strconv.Itoa(node.Val)+"->")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
|
||||||
1.递归版本
|
递归法:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
var binaryTreePaths = function(root) {
|
var binaryTreePaths = function(root) {
|
||||||
@ -518,6 +556,32 @@ var binaryTreePaths = function(root) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
迭代法:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var binaryTreePaths = function(root) {
|
||||||
|
if (!root) return [];
|
||||||
|
const stack = [root], paths = [''], res = [];
|
||||||
|
while (stack.length) {
|
||||||
|
const node = stack.pop();
|
||||||
|
let path = paths.pop();
|
||||||
|
if (!node.left && !node.right) { // 到叶子节点终止, 添加路径到结果中
|
||||||
|
res.push(path + node.val);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
path += node.val + '->';
|
||||||
|
if (node.right) { // 右节点存在
|
||||||
|
stack.push(node.right);
|
||||||
|
paths.push(path);
|
||||||
|
}
|
||||||
|
if (node.left) { // 左节点存在
|
||||||
|
stack.push(node.left);
|
||||||
|
paths.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user