【代码随想录day 16】 力扣 513.找树左下角的值
视频讲解:https://www.bilibili.com/video/BV1424y1Z7pn/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html#%E6%80%9D%E8%B7%AF
力扣题目:https://leetcode.cn/problems/find-bottom-left-tree-value/
这道题需要注意的是找的是二叉树最后一行的最左节点的值,所以要找最大深度,我们先遍历左子树,再遍历右子树,当最大深度改变时result才会改变,所以在遍历过程中必先遇到左节点,就是我们要找的值。
class Solution {
public://初始化最大深度和结果int maxDepth = INT_MIN;int result;void traversal(TreeNode *root, int depth){//判断中止条件,如果找到叶子节点就结束if(root->left == NULL && root->right == NULL){//如果深度比最大深度还大,更新最大深度if(depth > maxDepth){maxDepth=depth;result = root->val;}return;}//遍历左子树if(root->left){//深度+1depth++;//递归traversal(root->left, depth);//需要遍历其他路径,因此要回溯depth--;}//遍历右子树if(root->right){//深度+1depth++;//递归traversal(root->right, depth);//需要遍历其他路径,因此要回溯depth--;}return;}int findBottomLeftValue(TreeNode* root) {traversal(root, 0);return result;}
};