Find Bottom Left Tree Value

来源:互联网 发布:mac safari视频插件 编辑:程序博客网 时间:2024/05/29 19:41

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


一层一层的搜索,返回最后一层最开始的值



class Solution {

public:
    int findBottomLeftValue(TreeNode* root) {
        deque <TreeNode *> q1;
        deque <TreeNode *> q2;
        q1.push_back(root);
        int val;
        while(!q1.empty()||!q2.empty())
        {
            if(!q1.empty())
            {
                val=q1.front()->val;
                while(!q1.empty())
                {
                    if(q1.front()->left) q2.push_back(q1.front()->left);
                    if(q1.front()->right) q2.push_back(q1.front()->right);
                    q1.pop_front();
                }
            }
            if(!q2.empty())
            {
                val=q2.front()->val;
                while(!q2.empty())
                {
                    if(q2.front()->left) q1.push_back(q2.front()->left);
                    if(q2.front()->right) q1.push_back(q2.front()->right);
                    q2.pop_front();
                }
            }
        }
        return val;
    }
};
0 0
原创粉丝点击