From 429b504779d9981cd14329406ec9acbfd72cd76d Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Sun, 5 Sep 2021 21:38:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00257.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84.md?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E6=B3=95Java=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0257.二叉树的所有路径.md | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index 2984427f..6386c48d 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -367,6 +367,43 @@ class Solution { } } ``` +```java +// 解法2 +class Solution { + /** + * 迭代法 + */ + public List binaryTreePaths(TreeNode root) { + List result = new ArrayList<>(); + if (root == null) + return result; + Stack stack = new Stack<>(); + // 节点和路径同时入栈 + stack.push(root); + stack.push(root.val + ""); + while (!stack.isEmpty()) { + // 节点和路径同时出栈 + String path = (String) stack.pop(); + TreeNode node = (TreeNode) stack.pop(); + // 若找到叶子节点 + if (node.left == null && node.right == null) { + result.add(path); + } + //右子节点不为空 + if (node.right != null) { + stack.push(node.right); + stack.push(path + "->" + node.right.val); + } + //左子节点不为空 + if (node.left != null) { + stack.push(node.left); + stack.push(path + "->" + node.left.val); + } + } + return result; + } +} +``` Python: ```Python