513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)
找树左下角的值
非递归
- 非递归方式显然容易,不考虑递归方式
- 层序遍历即可
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int ans = root->val;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; ++i) {
TreeNode* node = que.front();
que.pop();
// 保存每层最左值
if (!i) ans = node->val;
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return ans;
}
};
本文详细介绍了如何使用层序遍历解决LeetCode中的找树左下角值问题,通过非递归的方式,从根节点开始,逐层遍历,最后得到树的左下角节点的值。算法思路清晰,代码实现简洁,适用于二叉树的类似问题。
387

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



