把二叉树先序遍历,变成一个链表,链表的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
原文地址:https://www.cnblogs.com/leetcoder/p/11330354.html
时间: 2024-10-07 11:00:49