[LeetCode] 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]
]
/**
 * 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<vector<int> > levelOrder(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<vector<int>> ans;
        if(root == NULL) return ans;
        vector<TreeNode*> cur;
        vector<int> curVal;
        cur.push_back(root);
        curVal.push_back(root -> val);
        while(!cur.empty())
        {
            ans.push_back(curVal);
            vector<TreeNode*> tmp;
            vector<int> tmpVal;
            for(int i = 0;i < cur.size();i++)
            {
                if(cur[i] -> left != NULL) 
                {
                    tmp.push_back(cur[i] -> left);
                    tmpVal.push_back(cur[i] -> left -> val);
                }
                if(cur[i] -> right != NULL) 
                {
                    tmp.push_back(cur[i] -> right);
                    tmpVal.push_back(cur[i] -> right -> val);
                }
            }
            cur = tmp;
            curVal = tmpVal;
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/changchengxiao/p/3417530.html