题目链接:Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:

Given binary tree {3,9,20,#,#,15,7},

    3 
   / \ 
  9  20 
    /  \ 
   15   7 

return its bottom-up level order traversal as:

[ 
  [15,7], 
  [9,20], 
  [3] 
] 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

1 / \ 2 3 / 4 \ 5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

这道题的要求是从下往上分层遍历二叉树。

和Binary Tree Level Order Traversal同样的思路,只不过在最后需要将数组反转即可。

由于需要把每层的节点分别放入到数组中,因此需要引入变量n记录每层的节点数量。剩下的,就是广度优先搜索的方法了。

广度优先搜索算法(Breadth First Search),又叫宽度优先搜索,或横向优先搜索。从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则算法中止。借助队列数据结构,由于队列是先进先出的顺序,因此可以先将左子树入队,然后再将右子树入队。这样一来,左子树结点就存在队头,可以先被访问到。

时间复杂度:O(n)

空间复杂度:O(n)

 1 class Solution
 2 {
 3 public:
 4     vector<vector<int> > levelOrderBottom(TreeNode *root)
 5     {
 6         vector<vector<int> > vvi;
 7         
 8         if(NULL == root)
 9             return vvi;
10         
11         queue<TreeNode *> q;
12         q.push(root);
13         while(!q.empty())
14         {
15             vector<int> vi;
16             for(int i = 0, n = q.size(); i < n; ++ i)
17             {
18                 TreeNode *temp = q.front();
19                 q.pop();
20                 if(temp -> left != NULL)
21                     q.push(temp -> left);
22                 if(temp -> right != NULL)
23                     q.push(temp -> right);
24                 vi.push_back(temp -> val);
25             }
26             vvi.push_back(vi);
27         }
28         reverse(vvi.begin(), vvi.end());
29         return vvi;
30     }
31 };