[Leetcode 77] 102 Binary Tree Level Order Traversal

Problem:

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]
]

Analysis:

The problem is an extension of the original level-order traversal problem. We need an extra sentinal node to signal the end of a level. 

Each time we encounter it, we know that a level is ended so we push the partial_result_vector into the result vector and then immediately push it into the queue again.

The quit condition switch from queue.empty() to there's only the sentinal node in the queue.

Code:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12 vector<vector<int> > levelOrder(TreeNode *root) {
13     // Start typing your C/C++ solution below
14     // DO NOT write int main() function
15     vector<vector<int> > res;
16     if (root == NULL)
17         return res;
18 
19     queue<TreeNode *> q;
20     q.push(root);
21 
22     TreeNode *tmp, *sentl;
23 
24     sentl = new TreeNode((1<<31));
25     sentl->left = sentl->right = NULL;
26     q.push(sentl);
27 
28     vector<int> pres;
29     while (!(q.size()==1 && q.front() == sentl)) {
30         tmp = q.front();
31         q.pop();
32 
33         if (tmp == sentl) {
34             res.push_back(pres);
35             pres.clear();
36             q.push(sentl);
37         } else {
38             pres.push_back(tmp->val);
39 
40             if (tmp->left != NULL)
41                 q.push(tmp->left);
42 
43             if (tmp->right != NULL)
44                 q.push(tmp->right);
45         }
46 
47     }
48 
49     res.push_back(pres);
50 
51     return res;
52 }
53 };
View Code
原文地址:https://www.cnblogs.com/freeneng/p/3205376.html