LeetCode:Find Bottom Left Tree Value

题目链接:https://leetcode.com/problems/find-bottom-left-tree-value/description/

解题思路:使用宽度优先搜索,搜索完一行的结点再继续下一行的结点,返回最后一行的左边第一个结点的值。

代码如下:

int findBottomLeftValue(TreeNode* root) {
        vector<TreeNode*> now_row;
        int result;
        if (root != NULL) {
            now_row.push_back(root);
            result = root->val;
            while(!now_row.empty()) {
                vector<TreeNode*> next_row;
                vector<int> row_val;
                for(int i = 0; i < now_row.size(); i++) {
                     TreeNode *temp = now_row[i];
                    if (temp->left != NULL) {
                        row_val.push_back(temp->left->val);
                        next_row.push_back(temp->left);
                    }
                    if (temp->right != NULL) {
                        row_val.push_back(temp->right->val);
                        next_row.push_back(temp->right);
                    }
                }
                now_row.clear();
                if (!next_row.empty()) {
                    for(int i = 0; i < next_row.size(); i++) {
                        now_row.push_back(next_row[i]);
                    }
                    result = now_row[0]->val;
                }
            }
        }
        return result;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值