leetcode 257 Binary Tree Paths

﹏ヽ暗。殇╰゛Y 2022-05-04 18:28 249阅读 0赞

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

  1. Input:
  2. 1
  3. / \
  4. 2 3
  5. \
  6. 5
  7. Output: ["1->2->5", "1->3"]
  8. Explanation: All root-to-leaf paths are: 1->2->5, 1->3

递归方法:

1、递归终止条件,root是否为空,及是否为叶子结点

2、递归过程

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public List<String> binaryTreePaths(TreeNode root) {
  12. List<String> res = new ArrayList<String>();
  13. if(root == null)
  14. return res;
  15. if(root.left == null && root.right == null){
  16. res.add(root.val + "");
  17. return res;
  18. }
  19. List<String> leftS = binaryTreePaths(root.left);
  20. for(int i=0;i<leftS.size();i++){
  21. res.add(root.val + "->" + leftS.get(i));
  22. }
  23. List<String> rightS = binaryTreePaths(root.right);
  24. for(int i=0;i<rightS.size();i++){
  25. res.add(root.val + "->" + rightS.get(i));
  26. }
  27. return res;
  28. }
  29. }

submission中 深度优先遍历DFS:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public List<String> binaryTreePaths(TreeNode root) {
  12. List<String> result = new LinkedList<>();
  13. dfs(result, root, "");
  14. return result;
  15. }
  16. private void dfs(List<String> result, TreeNode node, String s) {
  17. if (node == null) return;
  18. String built = s.length() == 0 ? s + node.val : s + "->" + node.val;
  19. if (node.left == null && node.right == null) {
  20. result.add(built);
  21. } else {
  22. dfs(result, node.left, built);
  23. dfs(result, node.right, built);
  24. }
  25. }
  26. }

发表评论

表情:
评论列表 (有 0 条评论,249人围观)

还没有评论,来说两句吧...

相关阅读