将二叉树拆成链表

来源:互联网 发布:网络课程数学文化答案 编辑:程序博客网 时间:2024/06/07 05:42

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

样例

              1               \     1          2    / \          \   2   5    =>    3  / \   \          \ 3   4   6          4                     \                      5                       \                        6
解题思路:创建一个新的树的vector,将系统给的树的所有节点用递归的方式添加到vector中,然后将vector中的元素都付给右子树,将左子树定义为空。

实验代码:

class Solution {
public:
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    vector<TreeNode*> temp;
    void flatten(TreeNode *root) {
        // write your code here
        if(root==NULL)
        return;
        tianjia(root);
        int i;
        for( i=0;i<temp.size()-1;i++)
        {
            temp[i]->left=NULL;
            temp[i]->right=temp[i+1];
        }
    }
    void tianjia(TreeNode* root)
    {
        if(root==NULL)
         return;
        temp.push_back(root);
        tianjia(root->left);
        tianjia(root->right);
    }
};

个人感想:循环的时候将树的左子树定义为空。

0 0
原创粉丝点击