首页 > 代码库 > LeetCode[Tree]: Binary Tree Zigzag Level Order Traversal
LeetCode[Tree]: Binary Tree Zigzag Level Order Traversal
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。