leetcode题解-513-找树左下角的值

题目

My way

dfs递归实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int res = -1;
int maxHeight = -1;
void dfs(TreeNode* root, int h)
{
if (!root) return;

if (!root->left && !root->right)
{
if (h > maxHeight)
{
maxHeight = h;
res = root->val;
}
}

dfs(root->left, h + 1);
dfs(root->right, h + 1);
}
public:
int findBottomLeftValue(TreeNode* root)
{
dfs(root, 0);
return res;
}
};

运用2个辅助变量:

  • res记录要返回的结点的val
  • maxHeight记录要返回的结点的高度,用来确认是最深一个结点上的值