Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input: 2 / \ 1 3 Output: 1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7
Note: You may assume the tree (i.e., the given root node) is not NULL.
思路:运用二叉树的层序遍历(宽度优先搜索),当到达最底层时,返回最底层中最左边节点的值。
一般来说,二叉树的层序遍历可以用queue来实现,从root节点开始,将非空的左右子节点压入queue中。但是这样难以确定是否已经到达最底层,需要额外增加一个queue记录对应节点所在的层数。
二叉树层序遍历的另外一种思路是用vector+两个标识来实现。类似queue的压栈做法,用两个标识cur和end来指示当前层的起始节点和结束节点的后一位。这样就可以通过这两个表示来判断是否已经到达最底层。代码如下
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
std::vector<TreeNode*> nVector;
int cur = 0;
int end = 0;
bool reach_bottom = false;
if (!root) return -1;
nVector.push_back(root);
while(cur < nVector.size()) {
end = nVector.size();
reach_bottom = true;
for(int i = cur;i < end; ++i) {
if(nVector[i]->left || nVector[i]->right) {
reach_bottom = false;
break;
}
}
if (reach_bottom) {
return nVector[cur]->val;
}
while (cur < end) {
if(nVector[cur]->left) nVector.push_back(nVector[cur]->left);
if(nVector[cur]->right) nVector.push_back(nVector[cur]->right);
++cur;
}
}
return -1;
}
};
优化:其实判断是否到达底部是没有必要的,只需要增加一个cur_left节点用来存储每层最左边节点。当宽度优先搜索结束后,cur_left就是最底层最左边节点。代码如下:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
std::vector<TreeNode*> nVector;
int cur = 0;
int end = 0;
TreeNode* cur_left = NULL;
bool reach_bottom = false;
if (!root) return -1;
nVector.push_back(root);
while(cur < nVector.size()) {
end = nVector.size();
cur_left = nVector[cur];
while (cur < end) {
if(nVector[cur]->left) nVector.push_back(nVector[cur]->left);
if(nVector[cur]->right) nVector.push_back(nVector[cur]->right);
++cur;
}
}
return cur_left->val;
}
};
另一种思路是进行深度优先搜索,记录深度,一旦发现现在的深度大于所记录的max depth,更新max depth和max depth value。(因为能够保证这时的节点是所在层最左边的节点)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void findBottomLeftValue(TreeNode* root, int& maxDepth, int& leftVal, int depth) {
if (root == NULL) {
return;
}
//Go to the left and right of each node
findBottomLeftValue(root->left, maxDepth, leftVal, depth+1);
//Update leftVal and maxDepth
findBottomLeftValue(root->right, maxDepth, leftVal, depth+1);
//Update leftVal and maxDepth
if (depth > maxDepth) {
maxDepth = depth;
leftVal = root->val;
}
}
//Entry function
int findBottomLeftValue(TreeNode* root) {
int maxDepth = 0;
//Initialize leftVal with root's value to cover the edge case with single node
int leftVal = root->val;
findBottomLeftValue(root, maxDepth, leftVal, 0);
return leftVal;
}
};
拓展:如果是返回最底层最右边节点的值呢?或者是计算数的最大深度?