列印樹的所有路徑
阿新 • • 發佈:2018-12-30
第一題是給了一棵樹 打出所有從root到leave的路徑
思路:遞迴DFS的方法,每次向兩邊孩子走,直到走到葉子節點為止。
public List<List<Integer>> res rightSideView(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); helper(root, res, new ArrayList<Integer>()); for (int i = 0; i < res.size(); i++) { System.out.println(res.get(i)); } return res; } private void helper(TreeNode root, List<List<Integer>> res, List<Integer> path) { if (root.left == null && root.right == null) { path.add(root.val); res.add(new ArrayList<>(path)); path.remove(path.size() - 1); return; } path.add(root.val); if (root.left != null) helper(root.left, res, path); if (root.right != null) helper(root.right, res, path); path.remove(path.size() - 1); return; }