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) {
        vector<vector<int> > result;
        result.clear();
        if(root == NULL)
            return result;
        
        vector<TreeNode *> q[2];
        int current = 1;
        int next = 0;
        q[0].push_back(root);
        
        while(q[next].empty() == false)
        {
            current = !current;
            next = !next;
            vector<int> tempVec;
            for(auto w : q[current])
            {
                tempVec.push_back(w->val);
                if(w->left)
                {
                    q[next].push_back(w->left);
                }
                if(w->right)
                {
                    q[next].push_back(w->right);
                }
            }
            result.push_back(tempVec);
            tempVec.clear();
            q[current].clear();
        }
        
        
        
        return result;
    }
};

解题思路:层次遍历,在处理层次遍历的代码中,巧妙的运用2个向量保存当前正在处理的层的节点q[current],和该层节点的儿子所组成的下一层节点q[next]在处理开始将current和next互换,轻松实现层次切换。再有就是遍历向量的写法for(auto w :q[current])是c++11的新特性,在编译器中不用通过。

posted @ 2014-12-01 13:49  ElephantKing  阅读(108)  评论(0编辑  收藏  举报