lintCode(453)——将二叉树拆分成链表
来源:互联网 发布:商城app源码下载 编辑:程序博客网 时间:2024/04/27 23:49
题目描述:将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
注意事项:不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
样例
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
挑战
不使用额外的空间耗费。
难度等级:容易
分析:本题采用递归的方法解决,关键是要知道由左子树转化的链表的头和尾,以及由右子树转化的链表的头和尾。头一定是二叉树的根节点,尾是右子树的尾(如果右子树不空)或者左子树的尾(如果右子树空,左子树不空)或者根(如果左右子树都是空)。
void flatten(TreeNode *root) {// main function if(root == NULL) return; ConvertToLink(root);}TreeNode* ConvertToLink(TreeNode* root) // utility function{// return value is the tail of the linked list if(root==NULL) return NULL; TreeNode* leftLinkTail = ConvertToLink(root->left); // tail of left linked list TreeNode* rightLinkTail = ConvertToLink(root->right); // tail of left linked list if(leftLinkTail != NULL) { leftLinkTail->right = root->right; root->right = root->left; } root->left = NULL; if(rightLinkTail!= NULL) return rightLinkTail; else if(leftLinkTail != NULL) return leftLinkTail; else return root;}
参考:http://blog.csdn.net/jiyanfeng1/article/details/41693439
0 0
- lintCode(453)——将二叉树拆分成链表
- lintcode 453 将二叉树拆分成链表
- 将二叉树拆分成链表-lintcode
- lintcode——将二叉树拆成链表
- LintCode:将二叉树拆成链表453
- [LintCode 453] 将二叉树拆成链表(Python)
- LintCode: 将二叉树拆成链表
- lintcode,将二叉树拆成链表
- LintCode 将二叉树拆成链表
- 将二叉树拆成链表-LintCode
- lintcode 将二叉树拆成链表
- lintcode将二叉树拆成链表
- LintCode 将二叉树拆成链表
- lintcode --将二叉树拆成链表
- 将二叉树拆成链表-LintCode
- lintCode(469)——等价二叉树
- lintcode——克隆二叉树
- lintcode——翻转二叉树
- leetcode_086 Partition List
- 认识自己
- Linux uptime --显示系统运行时间
- mysql安装卸载乱码等问题
- (OpenCV)SVM:从理论到OpenCV实践
- lintCode(453)——将二叉树拆分成链表
- 多线程的3中实现方式,以及有返回值线程池Demo
- 将dic里的数据写到model里,自动处理null数据
- Linux 常用命令简记
- doxygen注释
- Spring常用配置
- iOS 数据缓存
- Linux useradd --建立用户账号和用户起始目录
- 详解spring 每个jar的作用