跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:257. 二叉树的所有路径
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5]
输出:[“1->2->5”,“1->3”]
示例 2:
输入:root = [1]
输出:[“1”]
注意这里traversal
函数里面path
使用的是list
,是引用传递的,需要回溯;前序遍历,中左右
public List<String> binaryTreePaths(TreeNode root) {if (root == null)return new ArrayList<>();// 存放结果List<String> res = new ArrayList<>();// 存放当前的路径List<String> path = new ArrayList<>();traversal(root, path, res);return res;}private void traversal(TreeNode cur, List<String> path, List<String> res) {// 先将当前节点的val放入path中,这里不考虑NPE,非空的时候在调用该方法path.add(cur.val + "");// 如果当前节点是叶子节点if (cur.left == null && cur.right == null) {String temp = String.join("->", path);res.add(temp);}// 左子结点不为空才继续向左if (cur.left != null) {traversal(cur.left, path, res);// 这个remove就是回溯的过程!path.remove(path.size() - 1);}// 右子结点不为空才继续向右if (cur.right != null) {traversal(cur.right, path, res);path.remove(path.size() - 1);}}
和上面解法的区别就是初始的时候就往list里面放cur.val
了,这样在traversal
方法里面就仅剩:终止条件,单层递归逻辑(分别向左,右遍历),就是一个简单的前序遍历,中左右
public List<String> binaryTreePaths(TreeNode root) {if (root == null)return new ArrayList<>();// 存放结果List<String> res = new ArrayList<>();// 存放当前的路径List<String> path = new ArrayList<>();path.add(root.val + "");traversal(root, path, res);return res;}private void traversal(TreeNode cur, List<String> path, List<String> res) {// 如果当前节点是叶子节点if (cur.left == null && cur.right == null) {String temp = String.join("->", path);res.add(temp);}// 左子结点不为空才继续向左if (cur.left != null) {path.add(cur.left.val + "");traversal(cur.left, path, res);// 这个remove就是回溯的过程!path.remove(path.size() - 1);}// 右子结点不为空才继续向右if (cur.right != null) {path.add(cur.right.val + "");traversal(cur.right, path, res);path.remove(path.size() - 1);}}
精简版,traversal
方法参数中传的是字符串
public List<String> binaryTreePaths(TreeNode root) {if (root == null)return new ArrayList<>();List<String> res = new ArrayList<>();traversal(root, "", res);return res;}private void traversal(TreeNode cur, String path, List<String> res) {path += cur.val;if (cur.left == null && cur.right == null) {res.add(path);}if (cur.left != null) {traversal(cur.left, path + "->", res);}if (cur.right != null) {traversal(cur.right, path + "->", res);}}