diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index f902aab2..b15fa1be 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -469,6 +469,9 @@ class Solution: --- Go: + +递归法: + ```go func binaryTreePaths(root *TreeNode) []string { res := make([]string, 0) @@ -491,10 +494,45 @@ func binaryTreePaths(root *TreeNode) []string { 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: -1.递归版本 +递归法: ```javascript 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; +}; +```