【力扣刷题】513. 找树左下角的值
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:
输入: root = [2,1,3] 输出: 1
示例 2:
输入: [1,2,3,4,null,5,6,null,null,7] 输出: 7
提示:
- 二叉树的节点个数的范围是
[1,104]
-231 <= Node.val <= 231 - 1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans;
int ma=-1;
void traversal(TreeNode* root, int dep){
if(root->left==nullptr&&root->right==nullptr){
if(dep>ma){
ma=dep;
ans=root->val;
}
return;
}
if(root->left){
dep++;
traversal(root->left,dep);
dep--;
}
if(root->right){
dep++;
traversal(root->right,dep);
dep--;
}
return;
}
int findBottomLeftValue(TreeNode* root) {
traversal(root,0);
return ans;
}
};
层次遍历(迭代法)
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
int result = 0;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (i == 0) result = node->val; // 记录最后一行第一个元素
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return result;
}
};
版权声明:
作者:Zhang, Hongxing
链接:http://zhx.info/archives/663
来源:张鸿兴的学习历程
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
文章目录
关闭