Saturday, December 8, 2012

[leetcode] binary tree level traversal



Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector > levelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       
        // initialize the result
        vector > result;
       
        if (!root)
            return result;
       
        queue my_queue;
       
        my_queue.push(root);
        // push a dummy node into the queue
        my_queue.push(NULL);
       
        // initialize a tmp array
        vector tmp;
       
        while (!my_queue.empty())
        {
            TreeNode *front = my_queue.front();
           
            if (!front)
            {
                // process a dummy
                if (tmp.size() > 0)
                    result.push_back(tmp);
                tmp.erase(tmp.begin(), tmp.end());
                my_queue.pop();
                continue;
            }
            else
            {
                tmp.push_back(front->val);
                my_queue.pop();
            }
           
            if (front->left) my_queue.push(front->left);
            if (front->right) my_queue.push(front->right);
           
            // check if the next node is dummy
            front = my_queue.front();
            if (!front)
            {
                // initialize another dummy into the queue
                my_queue.push(NULL);
            }
        }
       
        return result;
    }
};

No comments: