淘宝笔试题:树的层遍历
2013-04-11 12:50
162 查看
淘宝笔试题:对于一颗完全二叉树,要求给所有节点加上一个pNext指针,指向同一层的相邻节点;如果当前节点已经是该层的最后一个节点,则将pNext指针指向NULL;给出程序实现,并分析时间复杂度和空间复杂度。
题目的只是层遍历的变形。。
朋友过来一起玩了几天,不亦乐乎。。。
结果写些code都是一堆一堆bug。。。
时间复杂度为O(n),空间复杂度为O(2^(ceil(logn)))即拥有最多节点层;
题目的只是层遍历的变形。。
朋友过来一起玩了几天,不亦乐乎。。。
结果写些code都是一堆一堆bug。。。
struct SBinaryTreeNode // a node of the binary tree { int m_nValue; // value of node SBinaryTreeNode *m_pLeft; // left child of node SBinaryTreeNode *m_pRight; // right child of node SBinaryTreeNode *m_pNext; }; void LevelOder(SBinaryTreeNode * root) { if (!root) { return ; } queue<SBinaryTreeNode*> q; SBinaryTreeNode *p; unsigned long i=1; unsigned long l=2; //level of .. q.push(root); while(!q.empty()) { p = q.front(); if (p->m_pLeft) { q.push(p->m_pLeft); } if (p->m_pRight) { q.push(p->m_pRight); } q.pop(); if (i == l-1) { //tail of this level l<<=1; p->m_pNext = NULL; } else { if (!q.empty()) { p->m_pNext = q.front(); } else { p->m_pNext = NULL; } } ++i; } }
时间复杂度为O(n),空间复杂度为O(2^(ceil(logn)))即拥有最多节点层;
相关文章推荐
- 2017校招 美团笔试题 编程题 层次遍历多叉树
- 人搜笔试编程题——树的层序遍历
- 笔试题-计算图中黑色瓷砖数(深度优先遍历的使用)
- 阿里笔试-二叉树由前序遍历和中序遍历推导后序遍历
- 淘宝2012笔试题——小白鼠试药
- 淘宝2012笔试中的一附加题
- Java nio 学习笔记(四) 淘宝2012校招技术笔试题
- 最近琐事——淘宝,笔试,合唱
- 笔试算法题(07):还原后序遍历数组 & 半翻转英文句段
- 淘宝2011.9.21校园招聘会笔试题 .
- 淘宝2012校园招聘笔试题
- 2011淘宝春季实习生招聘笔试题
- PHP笔试题——遍历文件目录
- 记淘宝2011实习招聘笔试
- 淘宝2011春季校园招聘笔试试题(答案+个人解析版)
- leetcode笔试题二叉树的前序、中序、后序遍历的递归和循环c++实现
- 二维数组的蛇形遍历 - 金山笔试题
- 转载--淘宝2012笔试题
- 2014淘宝笔试一题详解
- 笔试常见问题之子网掩码计算和二叉树的前中后遍历