mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加0257.二叉树的所有路径.md迭代法Java解法
This commit is contained in:
@ -367,6 +367,43 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 解法2
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* 迭代法
|
||||||
|
*/
|
||||||
|
public List<String> binaryTreePaths(TreeNode root) {
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
if (root == null)
|
||||||
|
return result;
|
||||||
|
Stack<Object> 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:
|
||||||
```Python
|
```Python
|
||||||
|
Reference in New Issue
Block a user