1.题目描述:
给你一个二叉树的根节点root,按任意顺序,返回所有从根节点到叶子节点的路径。叶子节点是指没有子节点的节点。
2.回溯:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
List<TreeNode> path = new ArrayList<>();
backtracking(root, path, res);
return res;
}
public void backtracking(TreeNode root, List<TreeNode> path, List<String> res) {
path.add(root);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size(); i++) {
sb.append(path.get(i).val + "->");
}
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
res.add(sb.toString());
return;
}
if (root.left != null) {
backtracking(root.left, path, res);
path.remove(path.size() - 1);
}
if (root.right != null) {
backtracking(root.right, path, res);
path.remove(path.size() - 1);
}
}
}
3. 广度迭代:层序依次遍历节点,并记录每一条路线。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
Queue<String> path = new LinkedList<>();
queue.offer(root);
path.offer(root.val + "");
while (!queue.isEmpty()) {
TreeNode temp = queue.poll();
String s = path.poll();
if (temp.left == null && temp.right == null) {
res.add(s);
}
if (temp.left != null) {
queue.offer(temp.left);
path.offer(new StringBuilder(s).append("->" + temp.left.val).toString());
}
if (temp.right != null) {
queue.offer(temp.right);
path.offer(new StringBuilder(s).append("->" + temp.right.val).toString());
}
}
return res;
}
}