码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Binary Tree Level Order Traversal II

时间:2015-11-29 14:58:47      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:(链接)

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.

解题思路

递归版:

/**
 * Definition for a binary tree node.
 * 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) {
        travel(root, 1);
        
        reverse(result.begin(), result.end());
        
        return result;
    }
    
    void travel(TreeNode *root, int level) {
        if (!root) return;
        if (level > result.size()) {
            result.push_back(vector<int>());
        }
        
        result[level - 1].push_back(root->val);
        travel(root->left, level + 1);
        travel(root->right, level + 1);
    }
private:
    vector<vector<int>> result;
};

迭代版:

 1 /**
 2  * Definition for a binary tree node.
 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>> levelOrderBottom(TreeNode* root) {
13         vector<vector<int>> result;
14         if (!root) return result;
15         
16         queue<TreeNode *> current, next;
17         vector<int> level;
18         current.push(root);
19         
20         while (!current.empty()) {
21             while (!current.empty()) {
22                 TreeNode *tmp = current.front();
23                 current.pop();
24                 level.push_back(tmp->val);
25                 
26                 if (tmp->left != nullptr) next.push(tmp->left);
27                 if (tmp->right != nullptr) next.push(tmp->right);
28             }
29             
30             result.push_back(level);
31             level.clear();
32             swap(current, next);
33         }
34         
35         reverse(result.begin(), result.end());
36         
37         return result;
38     }
39 };

 

[LeetCode]Binary Tree Level Order Traversal II

标签:

原文地址:http://www.cnblogs.com/skycore/p/5004734.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!