将二叉树拆成链表
问题描述:
将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的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题感悟:
我本来想的是在原树上构造单链表,结果写出来的代码调试得到的数据只有一小部分通过。在调代码的过程中,一定要学会变通,某种方法不行时,一定要果断放弃。
1403

被折叠的 条评论
为什么被折叠?



