C++ breath first traversal


  • 0
    B

    it is just another variation of breath first traversal

    the goal is to find the left most element of bottom level

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int findBottomLeftValue(TreeNode* root) {
            queue<TreeNode*>q;
            q.push(root);
            q.push(NULL);
            int ans = root -> val;
            while(q.size()>1)
            {
                auto e = q.front();
                q.pop();
                if(e)
                {
                    if(e->left) q.push(e->left);
                    if(e->right) q.push(e->right);
                }
                else
                {
                    ans = q.front()->val;
                    q.push(NULL);
                }
            }
            return ans;
        }
    };

Log in to reply
 

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