LintCode 将二叉树拆成链表

题目描述:
将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。

注意事项

不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。

您在真实的面试中是否遇到过这个题? Yes
样例
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6

思路分析:

将前序遍历保存在vector中。
再建树就行了。

ac代码:

/**
 * 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
     */
    vector<int> v;
    void dfs(TreeNode *root)
    {
        if(root==NULL)
            return ;
        v.push_back(root->val);
        dfs(root->left);
        dfs(root->right);
    }
    void flatten(TreeNode *root) {
        // write your code here
        dfs(root);
        TreeNode *r,*tal;
        tal=root;
        for(int i=1;i<v.size();i++)
        {
            r=new TreeNode(v[i]);
            tal->left=NULL;
            tal->right=r;
            tal=r;
        }
    }
};
发布了166 篇原创文章 · 获赞 4 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sinat_34336698/article/details/70038076