513. Find Bottom Left Tree Value(C++)

来源:互联网 发布:钢结构螺栓验算软件 编辑:程序博客网 时间:2024/06/03 15:40

題目


Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:    2   / \  1   3Output:1

Example 2: 

Input:        1       / \      2   3     /   / \    4   5   6       /      7Output:7

Note: You may assume the tree (i.e., the given root node) is not NULL.




解題思路

找到樹的最底層,然後返回最左邊的數值。





代碼

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        vector<TreeNode*> save, save2;
        save.push_back(root);
        
        while (1) {
            for(int i = 0; i < save.size(); i++) {
                if (save[i]->left != NULL)  save2.push_back(save[i]->left);
                if (save[i]->right != NULL)  save2.push_back(save[i]->right);
            }
            
            if (save2.size() == 0) {
                return save[0]->val;
            }
            else {
                save = save2;
                save2.clear();
            }
        }


    }
};





感想

忘了把save2清空,debug了好久……

原创粉丝点击