Leetcode257. 二叉树的所有路径
题目:
给定一个二叉树,返回所有从根节点到叶子节点的路径。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
题解:
迭代
scala代码:
def binaryTreePaths(root: TreeNode): List[String] = {
val paths = new util.LinkedList[String]()
if (root != null) {
val node_stack = new util.Stack[TreeNode]()
val path_stack = new util.Stack[String]()
node_stack.add(root)
path_stack.add(root.value.toString)
while (!node_stack.isEmpty) {
val node = node_stack.pop()
val path = path_stack.pop()
if (node.left == null && node.right == null) {
paths.add(path)
}
if (node.left != null) {
node_stack.add(node.left)
path_stack.add(path + "->" + node.left.value.toString)
}
if (node.right != null) {
node_stack.add(node.right)
path_stack.add(path + "->" + node.right.value.toString)
}
}
}
paths.asScala.toList
}
java代码:
public static List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if (root == null) return list;
Stack<TreeNode> node_stack = new Stack<>();
Stack<String> path_stack = new Stack<>();
node_stack.push(root);
path_stack.push(Integer.toString(root.value));
while (!node_stack.isEmpty()) {
TreeNode node = node_stack.pop();
String path = path_stack.pop();
if (node.left == null && node.right == null) {
list.add(path);
}
if (node.left != null) {
node_stack.push(node.left);
path_stack.push(path + "->" + node.left.value);
}
if (node.right != null) {
node_stack.push(node.right);
path_stack.push(path + "->" + node.right.value);
}
}
return list;
}