算法day45 找树左下角的值

题目描述
力扣513:找树左下角的值

解法一:递归
寻找树的最底层以及最左侧的节点,我们应该关注的实际上是两个点:第一,最底层,也即我们应该要能够维护深度,这样才能确保取得最底层的节点;第二,最左侧,也即最底层的最先出现的节点,所以我们在遍历时只需要更新每一层遇到的第一个节点。具体的代码如下。

 void traversal(TreeNode *cur,int depth,int & max_depth,int & res){
    if(cur == nullptr) return;
    //如果当前的深度大于最大深度,说明进入了新的一层,可以收集新一层遇见的第一个有效节点的值
    if(depth > max_depth){
        //更新最大深度
        max_depth = depth;
        res = cur -> val;
    }
    traversal(cur->left,depth+1,max_depth,res);
    traversal(cur->right,depth+1,max_depth,res);
}
int findBottomLeftValue(TreeNode* root) {
    int res = 0;
    //设置初始时最大深度为-1,这样使得递归程序可以推进
    int max_depth = -1;
    int depth = 0;
    traversal(root,depth,max_depth,res);
    return res;
}

时间复杂度:O(n)
空间复杂度:O(h)

解法二:层序+队列
思路就是按层序按个找,每一次也只记录每一层的第一个元素的值,最后当找到最后一层时返回。代码如下。

    int findBottomLeftValue(TreeNode* root) {
    queue<TreeNode*> que;
    int res{};
    if(root) que.push(root);
    while(!que.empty()){
        size_t size = que.size();
        res = que.back() -> val;
        if(size == 0){
            break;
        }
        while(size--){
            TreeNode* node = que.front();
            que.pop();
            if(node->right) que.push(node->right);
            if(node->left) que.push(node->left);  
        }
    }
    return res;
}

时间复杂度:O(N*M)
空间复杂度:O(N)

END

posted on 2025-07-14 09:27  sakura430  阅读(5)  评论(0)    收藏  举报