将二叉树拆成链表
来源:互联网 发布:淘宝小卖家申请直播 编辑:程序博客网 时间:2024/05/20 13:07
将二叉树拆成链表
问题描述:
将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的right 指针,来表示链表中的 next 指针。
样例
1 \ 1 2 / \ \ 2 5 => 3 / \ \ \ 3 4 6 4 \ 5 \ 6
解题思路:
前序遍历给定的树,把遍历到的所有结点存到一个新建的向量中,然后从该向量的开始迭代,构造单链表。
代码实现:
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
vector<TreeNode *> t;
void def(TreeNode *root)
{
if(root==NULL)
return;
t.push_back(root);
def(root->left);
def(root->right);
}
void flatten(TreeNode *root)
{
// write your code here
if(root==NULL)
return;
def(root);
int i;
for(i=0;i<t.size()-1;i++)
{
t[i]->left=NULL;
t[i]->right=t[i+1];
}
t[i]->left=NULL;
}
};
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
vector<TreeNode *> t;
void def(TreeNode *root)
{
if(root==NULL)
return;
t.push_back(root);
def(root->left);
def(root->right);
}
void flatten(TreeNode *root)
{
// write your code here
if(root==NULL)
return;
def(root);
int i;
for(i=0;i<t.size()-1;i++)
{
t[i]->left=NULL;
t[i]->right=t[i+1];
}
t[i]->left=NULL;
}
};
A题感悟:
我本来想的是在原树上构造单链表,结果写出来的代码调试得到的数据只有一小部分通过。在调代码的过程中,一定要学会变通,某种方法不行时,一定要果断放弃。
0 0
- 将二叉树拆成链表
- LintCode: 将二叉树拆成链表
- 将二叉树拆成链表
- lintcode,将二叉树拆成链表
- LintCode 将二叉树拆成链表
- 将二叉树拆成链表-LintCode
- 将二叉树拆成链表
- 将二叉树拆成链表
- lintcode 将二叉树拆成链表
- 将二叉树拆成链表
- 将二叉树拆成链表
- lintcode将二叉树拆成链表
- 将二叉树拆成链表
- 将二叉树拆成链表
- 将二叉树拆成链表
- 将二叉树拆成链表
- 将二叉树拆成链表
- 将二叉树拆成链表
- C++实验四-项目六:输出星号图
- 树状数组(转载修改添加)
- LeetCode 516. Longest Palindromic Subsequence 解题报告
- 【R-CNN系列目标检测】(2)SPP-Net算法
- 总结
- 将二叉树拆成链表
- 开方的用法
- 初始化列表
- 根据具体日期计算是一年的第几周和当月的第几周
- Android 使用android-async-http网络请求框架出现Header[]不识别错误的解决办法
- ubuntu-qq一样的截图软件
- hello world C#
- Smali相关的基础知识点
- 二叉树的所有路径