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

Binary Tree Level Order Traversal

时间:2015-03-10 17:01:03      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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

Solution:

  借助队列,层序遍历,在队列中记录这个节点是第几层的。在从队列中取节点,同层的放在一个vector中,如果新的一层的节点出现了,则把上一层的vector放入到vector的vector中。这样记录的是从上到下遍历的结果,把vector反转即可。代码如下,通过了leetcode的在线测试。

/**
 * 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> > vecRes;
        if (!root)
            return vecRes;
            
        queue<pair<TreeNode*, int> > nodeQue; // first is val, second is layer
        vector<vector<int> > vecWorker;
        vector<int> vec;
        nodeQue.push(make_pair(root, 1));
        int layer = 1;
        
        while (!nodeQue.empty()) {
            TreeNode* node = nodeQue.front().first;
            int nodeLayer = nodeQue.front().second;
            nodeQue.pop();
            if (nodeLayer > layer) {
                vecWorker.push_back(vec);
                vec.clear();
                layer = nodeLayer;
            }
            vec.push_back(node->val);
            if (node->left) {
                nodeQue.push(make_pair(node->left, nodeLayer+1));
            }
            if (node->right) {
                nodeQue.push(make_pair(node->right, nodeLayer+1));
            }
        }
        vecWorker.push_back(vec);
        
        for (int i = vecWorker.size()-1; i >= 0; i--) {
            vecRes.push_back(vecWorker[i]);
        }
        
        return vecRes;
    }
};

时间复杂度,O(n),n是树的节点数。

Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/litao-tech/p/4326123.html

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