给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入: 2 / \ 1 3 输出: 1
示例 2:
输入: 1 / \ 2 3 / / \ 4 5 6 / 7 输出: 7
注意: 您可以假设树(即给定的根节点)不为 NULL。
class Solution {
public:
int maxDepth;
int res;
int findBottomLeftValue(TreeNode* root)
{
maxDepth = 0;
GetAns(1, root);
return res;
}
void GetAns(int depth, TreeNode* root)
{
if(root == NULL)
return;
if(depth > maxDepth)
{
maxDepth = depth;
res = root ->val;
}
if(root ->left)
GetAns(depth + 1, root ->left);
if(root ->right)
GetAns(depth + 1, root ->right);
}
};
本文介绍了一种算法,该算法能够在给定的二叉树中找出最后一行最左侧的节点值。通过递归遍历的方式,记录下当前最大深度及对应的节点值,最终返回最底层最左侧的节点值。

被折叠的 条评论
为什么被折叠?



