深度优先遍历 递归
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
constructPaths(root,"",paths);
return paths;
}
public void constructPaths(TreeNode root, String path,List<String> paths) {
if (root != null) {
StringBuffer pathNew = new StringBuffer(path);
pathNew.append(Integer.toString(root.val));
if (root.left == null && root.right == null) {
paths.add(pathNew.toString());
} else {
pathNew.append("->");
constructPaths(root.left,pathNew.toString(),paths);
constructPaths(root.right,pathNew.toString(),paths);
}
}
}
}
深度优先遍历 迭代栈
广度优先遍历 迭代队列
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
if (root == null) {
return paths;
}
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
Queue<String> pathQueue = new LinkedList<String>();
nodeQueue.offer(root);
pathQueue.offer(Integer.toString(root.val));
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.poll();
String path = pathQueue.poll();
if (node.left == null && node.right == null) {
paths.add(path);
} else {
if (node.left != null) {
nodeQueue.offer(node.left);
pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString());
}
if (node.right != null) {
nodeQueue.offer(node.right);
pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString());
}
}
}
return paths;
}
}