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

LeetCode107——Binary Tree Level Order Traversal II

时间:2015-02-05 16:27:50      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:二叉树   c++   leetcode   

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

难度系数:

容易

实现

vector<TreeNode*> getLevelNode(vector<TreeNode*> &nodes)
{
    vector<TreeNode*> vtn;
    for (int i = 0; i < nodes.size(); ++i) {
        if (nodes[i]->left) {
            vtn.push_back(nodes[i]->left);
        }
        if (nodes[i]->right) {
            vtn.push_back(nodes[i]->right);
        }
    }
    return vtn;
}

vector<vector<int> > getLevelVal(vector<TreeNode*> &nodes)
{
    vector<vector<int> > vvi;
    if (nodes.size() == 0) {
        return vvi;
    }
    vector<TreeNode*> vtn = getLevelNode(nodes);
    vvi = getLevelVal(vtn);
    vector<int> vi;
    for (int i = 0; i < nodes.size(); ++i) {
        vi.push_back(nodes[i]->val);
    }
    vvi.push_back(vi);
    return vvi;
}

vector<vector<int> > levelOrderBottom(TreeNode *root) {
    vector<vector<int> > v;
    if (root == NULL) return v;
    vector<TreeNode*> nodes;
    nodes.push_back(root);
    return getLevelVal(nodes);
}

LeetCode107——Binary Tree Level Order Traversal II

标签:二叉树   c++   leetcode   

原文地址:http://blog.csdn.net/booirror/article/details/43528645

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