From 344dce02b36b6af546ccbe308c2e599f2b0312f0 Mon Sep 17 00:00:00 2001 From: Junwen Huang Date: Sat, 23 Oct 2021 10:32:35 +0800 Subject: [PATCH] =?UTF-8?q?Update=200257.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84.md=20=E2=80=94?= =?UTF-8?q?=E2=80=94=20=E5=A2=9E=E5=8A=A0go=E4=B8=8Ejs=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=9A=84=E9=80=92=E5=BD=92=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0257.二叉树的所有路径.md | 66 ++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) 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; +}; +```