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