小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
题意描述
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"]
示例 2:
输入:root = [1] 输出:["1"]
思路1:递归+剪枝
- 套用前序遍历递归模板
- 递归终止条件:叶子节点
- 递归终止,同时将这一分支的字符串加入到字符串数组中
class Solution {
List<String> result = new ArrayList<>();
private void helper(TreeNode root, String s, List<String> result) {
//一个分支终止递归
if(root.left == null && root.right == null) {
result.add(s);
return;
}
//递归遍历左子树
if(root.left != null) {
helper(root.left, s + "->" + root.left.val, result);
}
//递归遍历右子树
if(root.right != null) {
helper(root.right, s + "->" + root.right.val, result);
}
}
public List<String> binaryTreePaths(TreeNode root) {
//boundary case
if(root == null) {
return result;
}
String s = "" + root.val;
helper(root, s, result);
return result;
}
}
思路2:DFS
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (null == root) {
return result;
}
helper(root, result, String.valueOf(root.val));
return result;
}
private void helper(TreeNode node, List<String> result, String path) {
//对当前节点进行处理,如果左右节点为空说明到达叶子节点,加入结果集,返回
if (node.left == null && node.right == null) {
result.add(path);
return;
}
//处理左子树
if (node.left != null) {
helper(node.left, result, path + "->" + node.left.val);
}
//处理右子树
if (node.right != null) {
helper(node.right, result, path + "->" + node.right.val);
}
}
}
思路3:BFS
public List<String> bfs(TreeNode root){
List<String> res = new ArrayList<>();
if (root==null) return res;
Queue<TreeNode> nodeQueue = new LinkedList<>();
Queue<String> pathQueue = new LinkedList<>();
nodeQueue.offer(root);
pathQueue.offer(""+root.val);
TreeNode cur;
String path;
while (!nodeQueue.isEmpty()){
for (int i = nodeQueue.size(); i > 0; i--) {
cur = nodeQueue.poll();
path=pathQueue.poll();
//当前节点为叶节点,将路径添加到res中
if (cur.left==null&&cur.right==null)
res.add(path);
//子节点和子节点相关的字符串进入队列
if (cur.left!=null){
nodeQueue.offer(cur.left);
pathQueue.offer(path+"->"+cur.left.val);
}
if (cur.right!=null){
nodeQueue.offer(cur.right);
pathQueue.offer(path+"->"+cur.right.val);
}
}
}
return res;
}