您的位置:首页 > 产品设计 > UI/UE

No.513 Find Bottom Left Tree Value

2017-03-22 00:02 267 查看
思路一:

利用BFS将整个数组遍历,求出最底层最左边的节点,将该节点输出。在实现过程中利用队列数据结构实现,由于给定的树的节点的数据结构中没有记录层数的成员,所以同时创建一个记录层数的队列进行相同的操作。注意当层数发生第一次变化时,即每一层最左边的节点,记录该节点。

class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
queue<int> i;
q.push(root);
i.push(0);
int m = 0;
while(!q.empty()){
TreeNode* t = q.front();
int l = i.front();
if(t->left){
q.push(t->left);
i.push(l+1);
}
if(t->right){
q.push(t->right);
i.push(l+1);
}
if(l>m){
root = t;
}
m=l;
q.pop();
i.pop();
}
return root->val;
}
};思路二:
通过递归一个函数,每次传入当前节点,当前深度的最大值,当前层数最左边的节点和当前层的深度,如果到达根节点的子节点则停止递归,否则的话遍历当前节点的左右子树,如果当前的深度大于最大深度,则更新最大深度,而第一次更新深度的值的节点一定是每一层最左边的点,记录下来。

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);
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: