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},
这里写图片描述

return its level order traversal as:

这里写图片描述

代码

struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };

vector<vector<int>> levelOrder(TreeNode* root) {
       deque<TreeNode*>a;
       deque<TreeNode*>b;
       if (root)
            a.push_back(root);

       TreeNode*p = NULL;
       vector<vector<int>> result;

       while (!a.empty())
       {
           vector<int>temp;
           if (!a.empty() )
           {
                while (!a.empty() )
                {
               p = a.front();
               a.pop_front();
               temp.push_back(p->val);
               if (p->left)
                    b.push_back(p->left);
                if (p->right)
                    b.push_back(p->right);
                }
                result.push_back(temp);
           }

           while (!b.empty())
           {
               a.push_back(b.front());
               b.pop_front();
           }
       }
       return result;
    }
posted @ 2015-06-13 16:12  Rosanne  阅读(154)  评论(0编辑  收藏  举报