链接:
链接: 513. 找树左下角的值
描述,示例和提示:
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* node,int height,int& ret,int& retheight)
{
if(node==nullptr) return;
height++;
dfs(node->left,height,ret,retheight);
dfs(node->right,height,ret,retheight);
if(height>retheight)
{
ret = node->val;
retheight=height;
}
}
int findBottomLeftValue(TreeNode* root) {
int ret = 0;
int retheight=0;
dfs(root,0,ret,retheight);
return ret;
}
};
注意:
题目解析:
后续遍历就是从每个树的最左节点开始遍历,
(这是一张二叉树的图片)从中的后续遍历,我们就能知道为什么我们采用的是后续遍历
注意的点
引用需要初始化,我们的返回值高度retheight这个值不能刚开始就用0来代替传值