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

LeetCode[Tree]: Binary Tree Zigzag Level Order Traversal

时间:2014-12-26 16:46:08      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:递归   leetcode   迭代   zigzag   算法   

Given a binary tree, return the zigzag level order traversal of its nodes‘ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

我的迭代解法如下:

vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
    vector<vector<int> > res;

    vector<TreeNode *> iter;
    if (root) iter.push_back(root);

    int isForward = 1;
    while (!iter.empty()) {
        int size = iter.size();
        vector<int> level;

        for (int i = 0; i < size; ++i) {
            level.push_back(iter[i]->val);
            if (iter[i]->left) iter.push_back(iter[i]->left);
            if (iter[i]->right) iter.push_back(iter[i]->right);
        }

        if (!isForward) reverse(level.begin(), level.end());
        res.push_back(level);
        iter.erase(iter.begin(), iter.begin() + size);
        isForward ^= 0x01;
    }

    return res;
}


我的递归解法如下:

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        res.clear();
        if (!root) return res;
        zigzagLevelOrder(root, 1);
        return res;
    }

private:
    vector<vector<int> > res;

    void zigzagLevelOrder(TreeNode *root, int level) {
        if (res.size() < level) res.resize(level);
        if (level % 2) res[level - 1].push_back(root->val);
        else res[level - 1].insert(res[level - 1].begin(), root->val);

        if (root->left) zigzagLevelOrder(root->left, level + 1);
        if (root->right) zigzagLevelOrder(root->right, level + 1);
    }
};


两种算法的时间性能相同,如下图所示:

技术分享

LeetCode[Tree]: Binary Tree Zigzag Level Order Traversal

标签:递归   leetcode   迭代   zigzag   算法   

原文地址:http://blog.csdn.net/chfe007/article/details/42172633

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