513.找树左下角的值
力扣题目链接(opens new window)
给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
示例 2:
思路
迭代
迭代的思路最简单,只需层序记录每一层的第一个结点即可,代码如下:
class Solution {
public:int findBottomLeftValue(TreeNode* root) {queue<TreeNode*> qu;int res;if(root != nullptr)qu.push(root);while(!qu.empty()){int size = qu.size();for(int i=0;i<size;i++){TreeNode* node = qu.front(); qu.pop();if(i==0)res = node->val;if(node->left)qu.push(node->left);if(node->right)qu.push(node->right);}} return res;}
};
递归
递归的思路则不太好理解。首先要确定树左下角的值是指什么?是指深度最大的一层中的叶子结点。
因此我们用depth表示深度,取深度最大的结点赋值即可。
遍历顺序我们选用前序遍历。
class Solution {
private:int res;int maxdepth;
public:int findBottomLeftValue(TreeNode* root) {maxdepth = INT_MIN;dis(root,0);return res;}void dis(TreeNode* root, int depth){if(root->left == nullptr && root->right == nullptr){if(depth>maxdepth){maxdepth = depth;res = root->val;}}if(root->left){dis(root->left,depth+1);}if(root->right){dis(root->right,depth+1);}return ;}
};
dis(root->right,depth+1);}return ;
}
};