本文主要是介绍LeetCode - 103. 二叉树的锯齿形层序遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
描述
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
求解
// 暴力解法,利用两个栈实现vector<vector<int>> zigzagLevelOrder_vio(TreeNode *root) {if (root == nullptr) {return vector<vector<int>>();}// 利用栈辅助实现,从根节点开始,层序遍历中交换将左右子节点入栈,达到蛇形遍历的目的// 即当前层是左,右子节点入栈,则下层是右,子节点入栈int tag = 0;std::stack<TreeNode *> s1;s1.push(root);std::stack<TreeNode *> s2;vector<vector<int>> res;while (true) {if (tag == 0 && !s1.empty()) {tag = 1;vector<int> rec;rec.reserve(s1.size());while (!s1.empty()) {auto node = s1.top();s1.pop();rec.push_back(node->val);if (node->left) {s2.push(node->left);}if (node->right) {s2.push(node->right);}}res.emplace_back(std::move(rec));} else if (tag == 1 && !s2.empty()) {tag = 0;vector<int> rec;rec.reserve(s2.size());while (!s2.empty()) {auto node = s2.top();s2.pop();rec.push_back(node->val);if (node->right) {s1.push(node->right);}if (node->left) {s1.push(node->left);}}res.emplace_back(std::move(rec));} else {break;}}return res;}// 层序遍历 + 奇数层翻转vector<vector<int>> zigzagLevelOrder(TreeNode *root) {vector<vector<int>> res;if (root == nullptr) {return res;}std::queue<TreeNode *> q;q.push(root); // 根节点记为偶数层0,依次累加bool isLeftToRight = true;while (!q.empty()) {const int N = q.size();vector<int> record;record.reserve(N);for (int i = 0; i < N; ++i) {auto node = q.front();q.pop();record.push_back(node->val);if (node->left) {q.push(node->left);}if (node->right) {q.push(node->right);}}if (!isLeftToRight) {// 如果是奇数层,翻转结果std::reverse(record.begin(), record.end());}res.emplace_back(std::move(record));isLeftToRight = !isLeftToRight;}return res;}};
这篇关于LeetCode - 103. 二叉树的锯齿形层序遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!