Simple C++ and Python Solution - BFS


  • 0
    S

    Python:

    import Queue
    import sys
    class Solution(object):
        def largestValues(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            result = []
            if root is None:
                return result
            q = Queue.Queue()
            q.put(root)
            while not q.empty():
                len = q.qsize()
                max = -sys.maxint
                for i in range(0,len):
                    temp = q.get()
                    if temp.val > max:
                        max = temp.val
                    if temp.left:
                        q.put(temp.left)
                    if temp.right:
                        q.put(temp.right)
                result.append(max)
            return result
    

    C++ :

    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            queue<TreeNode*> q;
            vector<int> result;
            if(root==NULL) return result;
            q.push(root);
            int max;
            while(!q.empty())
            {
                int len = q.size();
                max = INT_MIN;
                for(int i=0;i<len;i++)
                {
                    TreeNode* temp = q.front();
                    q.pop();
                    if(temp->val > max)
                        max = temp->val;
                    if(temp->left)
                        q.push(temp->left);
                    if(temp->right)
                        q.push(temp->right);
                }
                result.push_back(max);
            }
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.