题目解析:这个问题的实质是要我们按成访问二叉树的结点,并返回每层访问的结果,这里要求走Z字,其实就是一行正向一行反向。
/* the kernel idea is visit a binary search tree in level and the additional work we have to label the end of one level. */ vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> > re; if(root == NULL) return re; queue<TreeNode*> visit; vector<int> level; visit.push(root); //NULL stands for the end of this level visit.push(NULL); //in store every level result, we are asked to change direction. bool reback = false; while (!visit.empty()) { TreeNode* cur = visit.front(); visit.pop(); if(cur != NULL){ if(cur->left) visit.push(cur->left); if(cur->right) visit.push(cur->right); level.push_back(cur->val); } else { if(reback) { vector<int> rlevel(level.rbegin(),level.rend()); re.push_back(rlevel); } else re.push_back(level); //remember to clear this level. level.clear(); reback = !reback; if(!visit.empty()) visit.push(NULL); } } return re; }
Binary Tree Zigzag Level Order Traversal,布布扣,bubuko.com
Binary Tree Zigzag Level Order Traversal
原文地址:http://blog.csdn.net/shiquxinkong/article/details/25904083