Lintcode---将二叉树拆成链表
2017-06-22 19:05
141 查看
将一棵二叉树按照前序遍历拆解成为一个
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
您在真实的面试中是否遇到过这个题?
Yes
样例
假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
您在真实的面试中是否遇到过这个题?
Yes
样例
1 \ 1 2 / \ \ 2 5 => 3 / \ \ \ 3 4 6 4 \ 5 \ 6 思路:采用递归的方法,按照先序遍历,将节点存放起来,放在一个容器中; 然后新建一个头结点指针,遍历容器中的节点,依次将节点连接成一个链表。 但是,要注意将左儿子标记为NULL;
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: a TreeNode, the root of the binary tree * @return: nothing */ /* 思路:采用递归的方法,按照先序遍历,先存放起来; 但是,要注意将左儿子标记为NULL; */ vector<TreeNode*> vec; vector<TreeNode*> Node(TreeNode* root,vector<TreeNode*>& vec){ if(root==NULL){ return vec; } vec.push_back(root); if(root->left!=NULL){ Node(root->left,vec); } if(root->right!=NULL){ Node(root->right,vec); } return vec; } void flatten(TreeNode *root) { // write your code here if(root==NULL){ return; } Node(root,vec); root=new TreeNode();//创建新的头结点指针; for(int i=0;i<vec.size();i++){ //多想想,第一次的写法为啥没有通过 vec[i]->left=NULL; root->right=vec[i]; root=root->right; } } };
相关文章推荐
- LintCode(Flatten Binary Tree to Linked List)翻转二叉树为链表 的变体
- LintCode:将二叉树拆成链表453
- lintcode flatten-binary-tree-to-linked-list 将二叉树拆成链表 前序扁平化 中序扁平化
- lintcode——将二叉树拆成链表
- lintcode:将二叉树拆成链表
- LintCode-链表划分
- LintCode-克隆二叉树
- Lintcode——链表插入排序
- LintCode:链表求和
- LintCode--合并k个排序链表
- Lintcode174——删除链表中倒数第n个节点
- LintCode_166_链表倒数第n个节点
- lintcode--二叉树的后序遍历
- lintcode :链表插入排序
- LintCode-在O(1)时间复杂度删除链表节点
- lintcode 85 在二叉树中插入节点
- LintCode—合并两个排序链表(165)
- lintcode——二叉树的中序遍历
- lintcode——翻转二叉树
- LintCode 二叉树的路径和