257. 二叉树的所有路径https://leetcode.cn/problems/binary-tree-paths/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
if (root != null) {
stack.push(root);
}
Stack<String> paths = new Stack<>();
paths.push(String.valueOf(root.val));
List<String> ans = new ArrayList<>();
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.println(paths.toString() + " " + ans + " " + (node == null ? stack.peek().val : node.val));
if (node != null) {
String path = paths.pop();
if (node.left == null && node.right == null) {
ans.add(path);
}
if (node.right != null) {
paths.push(path + "->" + node.right.val);
stack.push(node.right);
}
if (node.left != null) {
paths.push(path + "->" + node.left.val);
stack.push(node.left);
}
stack.push(node);
stack.push(null);
} else {
TreeNode pop = stack.pop();
if (pop.left == null && pop.right == null) {
ans.add(paths.pop());
}
}
}
return ans;
}
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
if (root != null) {
stack.push(root);
}
Stack<String> paths = new Stack<>();
paths.push(String.valueOf(root.val));
List<String> ans = new ArrayList<>();
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.println(paths.toString() + " " + ans + " " + (node == null ? stack.peek().val : node.val));
if (node != null) {
String path = paths.pop();
if (node.left == null && node.right == null) {
ans.add(path);
}
if (node.right != null) {
paths.push(path + "->" + node.right.val);
stack.push(node.right);
}
if (node.left != null) {
paths.push(path + "->" + node.left.val);
stack.push(node.left);
}
stack.push(node);
stack.push(null);
} else {
TreeNode pop = stack.pop();
}
}
return ans;
}
}
这里要注意下,之所以不在else里加答案,主要是因为,会重复if里的操作,还有为什么只要在if里加答案,是因为,每次if迭代推进栈的实际上是当前点的下一个点路径,这导致了,如果不在if里添加答案,当当前点被废弃时,它的路径path也会被废弃,这导致了尽管else可以遍历到每一个节点,但它对应的路径却已经在if中被消掉了
可以这么理解,实际上if是用来添加stack里的路径点的,并标记了应该如何出栈,同时最后也回收了弹出栈的点,else就是对栈内的点进行回收处理,这道题最大的问题就是paths里储存的信息和stack里的不一样,stack储存的是当前点,但是path里储存的却是当前点的左右子点,这产生了矛盾
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;
}
}