LeetCode Binary Tree Level Order Traversal 2

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

BFS, 之后倒序输出:
 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 
11 struct Node
12 {
13     TreeNode *node;
14     int level;
15     Node(){}
16     Node(TreeNode *n, int l):node(n), level(l){}
17 };
18 
19 class Solution {
20 private:
21     vector<vector<int> > ret;
22     vector<vector<int> > retReverse;
23 public:
24     vector<vector<int> > levelOrder(TreeNode *root) {
25         // Start typing your C/C++ solution below
26         // DO NOT write int main() function
27         ret.clear();
28         
29         if (root == NULL)
30             return ret;
31         
32         queue<Node> q;
33         
34         q.push(Node(root, 0));
35         
36         vector<int> a;
37         int curLevel = -1;
38         
39         while(!q.empty())
40         {
41             Node node = q.front();
42             if (node.node->left)
43                 q.push(Node(node.node->left, node.level + 1));
44             if (node.node->right)
45                 q.push(Node(node.node->right, node.level + 1));
46                 
47             if (curLevel != node.level)
48             {
49                 if (curLevel != -1)
50                     ret.push_back(a);
51                 curLevel = node.level;
52                 a.clear();
53                 a.push_back(node.node->val);                
54             }
55             else
56                 a.push_back(node.node->val);
57                 
58             q.pop();
59         }
60         
61         ret.push_back(a);
62         
63         retReverse.clear();
64         
65         for(int i = ret.size() - 1; i >= 0; i--)
66             retReverse.push_back(ret[i]);
67         
68         return retReverse;
69     }
70 };
posted @ 2012-10-27 22:15  chkkch  阅读(995)  评论(3编辑  收藏  举报