给定一个二叉树,使用原地算法将它 “压扁” 成链表。
示例:
给出:
1
/ \
2 5
/ \ \
3 4 6
压扁后变成如下:
1
\
2
\
3
\
4
\
5
\
6
提示:
如果您细心观察该扁平树,则会发现每个节点的右侧子节点是以原二叉树前序遍历的次序指向下一个节点的。
详见:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
方法一:递归解法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { if(root==nullptr) { return; } if(root->left) { flatten(root->left); } if(root->right) { flatten(root->right); } TreeNode *tmp=root->right; root->right=root->left; root->left=nullptr; while(root->right) { root=root->right; } root->right=tmp; } };
方法二:非递归解法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { if(root==nullptr) { return; } TreeNode* cur=root; while(cur) { if(cur->left) { TreeNode *p=cur->left; while(p->right) { p=p->right; } p->right=cur->right; cur->right=cur->left; cur->left=nullptr; } cur=cur->right; } } };
参考:https://www.cnblogs.com/grandyang/p/4293853.html