[leetcode]Binary Tree Zigzag Level Order Traversal
Posted on 2014-01-19 00:15 1957 阅读(155) 评论(0) 编辑 收藏 举报DFS,用一个变量来记录方向
从左往右就是push_back
从右往左就是push_front ,木有这个函数就用vec.insert(vec.begin() , val),虽然效率不怎样
/** * 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> > ans; if(root == nullptr) return ans; dfs(ans , root , 0 , true); return ans; } private: void dfs(vector<vector<int> >&ans , TreeNode* root , int dep , bool left) { if(root == nullptr) return; if(dep + 1 > ans.size()) ans.push_back(vector<int>()); if(left) ans[dep].push_back(root->val); else ans[dep].insert(ans[dep].begin() , root->val); dfs(ans , root->left,dep+1,!left); dfs(ans , root->right,dep+1,!left); } };
by 1957