首页 > 代码库 > 二叉树的层次遍历 II

二叉树的层次遍历 II

二叉树的层次遍历 II 

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

样例

给出一棵二叉树 {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

按照从下往上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]
标签 
二叉树 队列 二叉树遍历 宽度优先搜索
 
 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13  
14  
15 class Solution {
16     /**
17      * @param root : The root of binary tree.
18      * @return : buttom-up level order a list of lists of integer
19      */
20 public:
21     vector<vector<int>> levelOrderBottom(TreeNode *root) {
22         // write your code here
23         
24         vector<vector<int> > order;
25         queue<TreeNode*> queue;
26         int len;
27 
28         if(root == NULL)  {
29             return order;
30         }
31 
32         queue.push(root);
33         len = queue.size();
34 
35         while(!queue.empty())  {  
36             vector<int> base;  
37             len = queue.size();  
38   
39             while(len--)  {
40                 TreeNode *tmp=queue.front();  
41                 base.push_back(tmp->val);
42                 queue.pop();  
43                 if(tmp->left)  
44                     queue.push(tmp->left);  
45                 if(tmp->right)      
46                     queue.push(tmp->right);  
47             }  
48             order.push_back(base);  
49         }  
50 
51         vector<vector<int> > order2;
52         int i;
53     
54         for(i=order.size()-1; i>=0; i--) {
55             order2.push_back(order[i]);
56         }
57 
58         return order2;
59     }
60 };

 

二叉树的层次遍历 II