首页 > 代码库 > Binary Tree Zigzag Level Order Traversal
Binary Tree Zigzag Level Order Traversal
原题:
题目解析:这个问题的实质是要我们按成访问二叉树的结点,并返回每层访问的结果,这里要求走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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。