Binary Tree Zigzag Level Order Traversal
Total Accepted: 31183 Total Submissions: 117840My Submissions
Question Solution
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Hide Tags
Tree Breadth-first Search Stack
Have you met this question in a real interview?
Yes
No
#include<iostream> #include<queue> #include<stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /*这道题采用的是广度优先搜索的算法,对着二叉树一层一层的遍历,而对于题目中的要求,需要在先向右 又接着向左遍历,所以应用了栈,在偶数行时,先将结点压入栈中,再依次输入到vector中 */ vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> > last_result;//最终的存放结果的vector if(root==NULL) return last_result; TreeNode* temp_node; queue<TreeNode*> temp; int row_size=1;//每一层结点的个数 temp.push(root); int deepth=1;//层数 while(!temp.empty()) { vector<int> temp_relust; stack<int> temp_stack; while(row_size--)//每一层遍历 { temp_node=temp.front(); temp.pop(); if(temp_node->left!=NULL) temp.push(temp_node->left); if(temp_node->right!=NULL) temp.push((temp_node->right)); if(deepth%2==0)//偶数层的压栈 { temp_stack.push(temp_node->val); } else temp_relust.push_back(temp_node->val); } if(deepth%2==0)//偶数层的出栈 { while(!temp_stack.empty()) { temp_relust.push_back(temp_stack.top()); temp_stack.pop(); } } row_size=temp.size(); last_result.push_back(temp_relust); deepth++; } return last_result; } int main() { }
时间: 2024-12-11 13:44:45