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

题意:给一棵二叉树,返回层次遍历后,从叶节点到根回溯的结果。

解题思路:对二叉树进行层次遍历,用count来记录每层的结点数,用队列que实现,最后将层次遍历的结果反序则可。代码应该不难看懂。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        vector<vector<int> > ans;
        vector<vector<int> > result;
TreeNode* cur;
int count = 0; queue<TreeNode*> que; if(root != NULL) {
//先处理根结点 vector
<int> tmp; tmp.push_back(root->val); ans.push_back(tmp); if(root->left != NULL) { count++; que.push(root->left); } if(root->right != NULL){ count++; que.push(root->right); } while(!que.empty()) { int k = count; vector<int> tt; count = 0; for(int i=0;i<k; i++) { cur = que.front(); que.pop(); tt.push_back(cur->val); if(cur->left != NULL) { count++; que.push(cur->left); } if(cur->right != NULL){ count++; que.push(cur->right); } } ans.push_back(tt); } } if(ans.size() > 0) { for(int j = ans.size()-1; j >= 0; j--) result.push_back(ans[j]); } return result; } };

 

posted on 2014-05-09 21:00  bbking  阅读(177)  评论(0编辑  收藏  举报

导航