leetcode 513. 找树左下角的值
给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入:
2
/
1 3
输出:
1
示例 2:
输入:
1
/ \
2 3
/ / \
4 5 6
/
7
输出:
7
迭代思路
利用队列每次保存一层的节点,利用一个value记录当前层的最左边的节点值,层序遍历,每次更新value为当前层的最左侧的值,当队列为空时,value为最后一层的最左的值
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
que.push(root);
int value = 0;
while(!que.empty())
{
value = que.front()->val; //保存每一层的最左边的值
int size = que.size();
for(int i = 0; i < size; ++i)
{
TreeNode* node = que.front();
que.pop();
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
}
}
return value;
}
递归
参数和返回值:输入当前树的节点 TreeNode*;输出当前树的最左侧节点的值 int
单层逻辑:当前节点受否到达最底层,是则更新树的最大深度和最左侧的值
终止条件:当前节点为空
int maxDepth = 0;
int curDepth = 0;
int value = 0;
public:
int findBottomLeftValue(TreeNode* root) {
++curDepth;
if(root == nullptr)
return 0;
if(curDepth >= maxDepth)
{
value = root->val;
maxDepth = curDepth;
}
findBottomLeftValue(root->right);
--curDepth;
findBottomLeftValue(root->left);
--curDepth;
return value;
}