思路
首先,定义最大深度为 INT_MIN ,以及最大深度时的节点值res为0;
其次,先序遍历,在访问每个节点时,都判断是否是叶节点,如果是叶节点,在判断此时节点的深度是否大于前一次状态的最大深度,如果满足,更新最大深度,以及最大深度的节点的val。
最后输出res即可。其实如果用先序遍历,算是求深度的一个拓展,算是简单题的一种了。
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ void preorder(struct TreeNode* root,int depth,int* maxdepth,int* res){ if(root == NULL){ return ; } if(root -> left == NULL && root -> right == NULL){ if(depth > *maxdepth){ *maxdepth = depth; *res = root -> val; } } preorder(root -> left,depth + 1, maxdepth,res); preorder(root -> right,depth + 1, maxdepth,res); } int findBottomLeftValue(struct TreeNode* root) { int maxdepth = INT_MIN; struct TreeNode* maxroot = root; int res = 0; preorder(root,1,&maxdepth,&res); return res; } 作者:睡个好觉 链接:https://leetcode.cn/problems/find-bottom-left-tree-value/solutions/3623348/zhao-shu-zuo-xia-jiao-de-zhi-shi-ji-shan-y9bo/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。