码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-08-10 10:09:03      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:root   递归函数   style   http   sim   函数   tail   指针   imp   

把二叉树先序遍历,变成一个链表,链表的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

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

标签:root   递归函数   style   http   sim   函数   tail   指针   imp   

原文地址:https://www.cnblogs.com/leetcoder/p/11330354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!