LeetCode(103): 二叉树的锯齿形层次遍历
2023-09-14 08:59:35 时间
Medium!
题目描述:
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
解题思路:
这道二叉树的之字形层序遍历是之前那道[LeetCode] Binary Tree Level Order Traversal 二叉树层序遍历的变形,不同之处在于一行是从左到右遍历,下一行是从右往左遍历,交叉往返的之字形的层序遍历。根据其特点,我们想到栈也有后进先出的特点,这道题我们维护两个栈,相邻两行分别存到两个栈中,进栈的顺序也不相同,一个栈是先进左子结点然后右子节点,另一个栈是先进右子节点然后左子结点,这样出栈的顺序就是我们想要的之字形了。
C++解法一:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int> > zigzagLevelOrder(TreeNode *root) { 13 vector<vector<int> >res; 14 if (!root) return res; 15 stack<TreeNode*> s1; 16 stack<TreeNode*> s2; 17 s1.push(root); 18 vector<int> out; 19 while (!s1.empty() || !s2.empty()) { 20 while (!s1.empty()) { 21 TreeNode *cur = s1.top(); 22 s1.pop(); 23 out.push_back(cur->val); 24 if (cur->left) s2.push(cur->left); 25 if (cur->right) s2.push(cur->right); 26 } 27 if (!out.empty()) res.push_back(out); 28 out.clear(); 29 while (!s2.empty()) { 30 TreeNode *cur = s2.top(); 31 s2.pop(); 32 out.push_back(cur->val); 33 if (cur->right) s1.push(cur->right); 34 if (cur->left) s1.push(cur->left); 35 } 36 if (!out.empty()) res.push_back(out); 37 out.clear(); 38 } 39 return res; 40 } 41 };
比如对于题干中的那个例子:
3 / \ 9 20 / \ 15 7
我们来看每一层两个栈s1, s2的情况:
s1: 3
s2:
s1:
s2: 9 20
s1: 7 15
s2:
相关文章
- ☆打卡算法☆LeetCode 222. 完全二叉树的节点个数 算法解析
- ☆打卡算法☆LeetCode 226. 翻转二叉树 算法解析
- [LeetCode]238. 除自身以外数组的乘积
- 拼写单词(leetcode 1160)
- LeetCode笔记:Biweekly Contest 84
- LeetCode 算法题系列(第一周 25道)
- 《三战Leetcode》寻找有序数组的中位数
- Leetcode 题目070-爬楼梯
- JavaScript刷LeetCode拿offer-二叉树层序遍历篇
- 前端工程师leetcode算法面试必备-二叉树深度广度遍历
- 前端工程师leetcode算法面试必备-二叉树的构造和遍历
- 【day03】LeetCode(力扣)每日一刷[239. 滑动窗口最大值 ][1422. 分割字符串的最大得分][1046. 最后一块石头的重量 ]
- Binary Tree Postorder Traversal — LeetCode
- JavaScript刷LeetCode拿offer-二叉树层序遍历篇_2023-02-28
- 前端工程师leetcode算法之二叉树的构造和遍历
- LeetCode 算法题
- leetcode:合并两个有序数组
- Leetcode 111. 二叉树的最小深
- leetcode: 二叉树的层序遍历
- LeetCode——遍历序列构造二叉树