Leetcode 257.二叉树的所有路径
题目要求
示例 1:

输入:root = [1,2,3,null,5]
输出:[“1->2->5”,“1->3”]
示例 2:
输入:root = [1]
输出:[“1”]
前序遍历求二叉树路径
注意点:回溯和递归是一一对应的,有一个递归,就要有一个回溯,所以递归和回溯应该在一个大括号内
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<String>(); if (root == null) { return res; }
List<Integer> paths = new ArrayList<>(); travelsal(root, paths, res); return res; }
public void travelsal(TreeNode root, List<Integer> paths, List<String> res) { paths.add(root.val);
if (root.left == null && root.right == null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < paths.size() - 1; i++) { sb.append(paths.get(i)).append("->"); } sb.append(root.val); res.add(sb.toString()); return; }
if (root.left != null) { travelsal(root.left, paths, res); paths.remove(paths.size() - 1); } if (root.right != null) { travelsal(root.right, paths, res); paths.remove(paths.size() - 1); } } }
|
精简版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) { deal(root, ""); return result; }
public void deal(TreeNode node, String s) { if (node == null) return; if (node.left == null && node.right == null) { result.add(new StringBuilder(s).append(node.val).toString()); return; } String tmp = new StringBuilder(s).append(node.val).append("->").toString(); deal(node.left, tmp); deal(node.right, tmp); } }
|