leetcode 112. Path Sum DFS深度优先遍历

以你之姓@ 2022-06-08 03:17 310阅读 0赞

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

这道题考察的就是每一条路径的sum,找到target即可。

代码如下:

  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. public class Solution
  12. {
  13. List<Integer> res=new ArrayList<Integer>();
  14. public boolean hasPathSum(TreeNode root, int sum)
  15. {
  16. if(root==null)
  17. return false;
  18. else
  19. return bydfs(root,sum);
  20. }
  21. public boolean bydfs(TreeNode root, int sum)
  22. {
  23. if(root!=null)
  24. {
  25. if(root.left==null && root.right==null)
  26. return root.val==sum;
  27. boolean left = bydfs(root.left, sum-root.val);
  28. boolean right = bydfs(root.right, sum-root.val);
  29. return left || right;
  30. }else
  31. return false;
  32. }
  33. }

下面是C++的做法,就是做一个DFS深度优先遍历

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. /*
  5. struct TreeNode
  6. {
  7. int val;
  8. TreeNode *left;
  9. TreeNode *right;
  10. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  11. };
  12. */
  13. class Solution
  14. {
  15. public:
  16. bool hasPathSum(TreeNode* root, int sum)
  17. {
  18. return bydfs(root, 0, sum);
  19. }
  20. bool bydfs(TreeNode* root, int a, int sum)
  21. {
  22. if (root == NULL)
  23. return false;
  24. else
  25. {
  26. if (root->left == NULL && root->right == NULL)
  27. {
  28. if (a + root->val == sum)
  29. return true;
  30. else
  31. return false;
  32. }
  33. else
  34. {
  35. bool left = bydfs(root->left, a + root->val, sum);
  36. bool right = bydfs(root->right, a + root->val, sum);
  37. return left || right;
  38. }
  39. }
  40. }
  41. };

发表评论

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

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

相关阅读