lintcode 453 将二叉树拆成链表

将二叉树拆成链表

 

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

注意事项

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

样例
              1
               \
     1          2
    / \          \
   2   5    =>    3
  / \   \          \
 3   4   6          4
                     \
                      5
                       \
                        6
挑战

不使用额外的空间耗费。

 

 

这道题目很有趣的一点就是拆成右斜树的假链表,并且这道题目是按照前序遍历拆解,并不是按照数据大小拆解。

所以很容易的一个递归。

有两点需要思考,从哪里开始?(前序遍历)怎么拆?(保存左右儿子)

        

/**
 * 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: 
     */
    void flatten(TreeNode * root) {
        // write your code here
        if(root==NULL)
            return;
        TreeNode *l=root->left;
        TreeNode *r=root->right;
        flatten(root->left);
        flatten(root->right);
        if(root->left==NULL)
            return ;
        else {
            TreeNode *t=root->left;
            while(t->right)
                t=t->right;
            root->left=NULL;
            root->right=l;
            t->right=r;
        }
        return;
    }
};

  

 

 

 

posted @ 2017-09-19 21:54  会飞的雅蠛蝶  阅读(494)  评论(0编辑  收藏  举报