leetcode 513. Find Bottom Left Tree Value 最左边的值 + 一个简单的DFS深度优先遍历

柔情只为你懂 2022-06-02 22:50 203阅读 0赞

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:
Input:

  1. 2
  2. / \
  3. 1 3

Output:
1
Example 2:
Input:

  1. 1
  2. / \
  3. 2 3
  4. / / \
  5. 4 5 6
  6. /
  7. 7

Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.

题意很简单,直接做DFS深度优先遍历即可,在遍历的时候作比较即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <cmath>
  14. using namespace std;
  15. /*
  16. struct TreeNode
  17. {
  18. int val;
  19. TreeNode *left;
  20. TreeNode *right;
  21. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  22. };
  23. */
  24. class Solution
  25. {
  26. public:
  27. int findBottomLeftValue(TreeNode* root)
  28. {
  29. if (root == NULL)
  30. return 0;
  31. int maxDepth = 0 , res = root->val;
  32. getAll(root,maxDepth,0,res);
  33. return res;
  34. }
  35. void getAll(TreeNode* root, int& maxDepth, int depth,int& res)
  36. {
  37. if (root == NULL)
  38. return;
  39. else
  40. {
  41. getAll(root->left, maxDepth, depth + 1, res);
  42. getAll(root->right, maxDepth, depth + 1, res);
  43. if (depth > maxDepth)
  44. {
  45. maxDepth = depth;
  46. res = root->val;
  47. }
  48. return;
  49. }
  50. }
  51. };

发表评论

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

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

相关阅读