leetcode 257. Binary Tree Paths 深度优先遍历DFS

约定不等于承诺〃 2022-06-08 12:50 226阅读 0赞

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

For example, given the following binary tree:

1
/ \
2 3
\
5
All root-to-leaf paths are:

[“1->2->5”, “1->3”]

直接DFS深度优先遍历即可。

代码如下:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /*class TreeNode
  4. {
  5. int val;
  6. TreeNode left;
  7. TreeNode right;
  8. TreeNode(int x) { val = x; }
  9. }*/
  10. /*
  11. * 这道题其实很简单,但是要注意递归开始的起点和终点
  12. * Java中使用StringBuilder会更快点
  13. * */
  14. public class Solution
  15. {
  16. List<String> res=new ArrayList<String>();
  17. public List<String> binaryTreePaths(TreeNode root)
  18. {
  19. if(root==null)
  20. return res;
  21. //getAllPath(root,root.val+"");
  22. List<Integer> one=new ArrayList<>();
  23. one.add(root.val);
  24. getAllPath(root, one);
  25. return res;
  26. }
  27. private void getAllPath(TreeNode root, List<Integer> one)
  28. {
  29. if(root.left==null && root.right==null)
  30. {
  31. if(one.size()==1)
  32. res.add(one.get(0)+"");
  33. else
  34. {
  35. StringBuilder lastBuilder=new StringBuilder();
  36. lastBuilder.append(one.get(0));
  37. for(int i=1;i<one.size();i++)
  38. lastBuilder.append("->"+one.get(i));
  39. res.add(lastBuilder.toString());
  40. }
  41. }
  42. if(root.left!=null)
  43. {
  44. one.add(root.left.val);
  45. getAllPath(root.left, one);
  46. one.remove(one.size()-1);
  47. }
  48. if(root.right!=null)
  49. {
  50. one.add(root.right.val);
  51. getAllPath(root.right, one);
  52. one.remove(one.size()-1);
  53. }
  54. }
  55. private void getAllPath(TreeNode root, String path)
  56. {
  57. if(root.left==null && root.right==null)
  58. res.add(path);
  59. if(root.left!=null)
  60. getAllPath(root.left, path+"->"+root.left.val);
  61. if(root.right!=null)
  62. getAllPath(root.right, path+"->"+root.right.val);
  63. }
  64. }

下面是C++的做法,就是做一个简单的DFS深度优先遍历,代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5. /*
  6. struct TreeNode
  7. {
  8. int val;
  9. TreeNode *left;
  10. TreeNode *right;
  11. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  12. };
  13. */
  14. class Solution
  15. {
  16. public:
  17. vector<string> res;
  18. vector<string> binaryTreePaths(TreeNode* root)
  19. {
  20. if (root == NULL)
  21. return res;
  22. getAll(root, to_string(root->val));
  23. return res;
  24. }
  25. void getAll(TreeNode* root, string one)
  26. {
  27. if (root->left == NULL && root->right == NULL)
  28. res.push_back(one);
  29. if (root->left != NULL)
  30. getAll(root->left, one + "->" + to_string(root->left->val));
  31. if (root->right != NULL)
  32. getAll(root->right, one + "->" + to_string(root->right->val));
  33. }
  34. };

发表评论

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

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

相关阅读