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] ]
用stack, 从左到右,从右到左,轮着先入栈就行。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> > result; if (root == NULL) { return result; } bool from_left = true; TreeNode *cur; stack<TreeNode*> nodes, tmp; nodes.push(root); do { vector<int> level; while (!nodes.empty()) { cur = nodes.top(); nodes.pop(); level.push_back(cur->val); if (from_left) { if (cur->left != NULL) { tmp.push(cur->left); } if (cur->right != NULL) { tmp.push(cur->right); } } else { if (cur->right != NULL) { tmp.push(cur->right); } if (cur->left != NULL) { tmp.push(cur->left); } } } result.push_back(level); swap(nodes, tmp); from_left = !from_left; } while (!nodes.empty()); return result; } };
=====================第二次========================
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int>> result; bool from_left = true; stack<TreeNode*> first; stack<TreeNode*> second; first.push(root); vector<int> level; TreeNode *cur = NULL; while (!first.empty()) { while (!first.empty()) { cur = first.top(); first.pop(); if (cur != NULL) { level.push_back(cur->val); if (from_left) { second.push(cur->left); second.push(cur->right); } else { second.push(cur->right); second.push(cur->left); } } } if (!level.empty()) { result.push_back(level); level.clear(); } first.swap(second); from_left = !from_left; } return result; } };