LeetCode 114. Flatten Binary Tree to Linked List 动态演示

把二叉树先序遍历,变成一个链表,链表的next指针用right代替

用递归的办法先序遍历,递归函数要返回子树变成链表之后的最后一个元素

 

class Solution {
public:
    void helper(TreeNode* cur, TreeNode*& tail){           
        //a(tail)
        //lk("root",tail)
        //a(cur)
        //lk("root",cur)
        //dsp
        tail=cur;
        TreeNode* right=cur->right;
        //a(right)
        //lk("root",right)
        if(cur->left){
            TreeNode *leftTail=NULL; 
            helper(cur->left, leftTail);                        
            cur->right=cur->left;
            cur->left=NULL;
            tail=leftTail;
            //dsp
        }
        
        if(right){
            TreeNode *rightTail=NULL;
            helper(right, rightTail);
            tail->right=right;
            tail=rightTail;
            //dsp
        }
    }
    
    void flatten(TreeNode* root) {        
        if(!root)
            return;
        //ahd(root)
        
        TreeNode *tail=NULL;
        helper(root, tail);        
    }
};

程序运行动态演示:http://simpledsp.com/FS/Html/lc114.html

posted @ 2019-08-10 04:11  刷题不挨踢  阅读(139)  评论(0编辑  收藏  举报