Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
====================================================================================
题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
题目大意:将二叉树按照先序遍历的顺序转换成一个只有右子树的二叉树(一条链表),要求空间复杂度为O(1)。
思路1:通过先序遍历边搜边转换,由于过程的操作有点复杂,我选择用另外一种做法。
思路2:递归调用,假设函数flattenTree能符合题意地转成一棵新的二叉树树,则root节点的右子树等于flattenTree(root的左子树),转换完之后左子树的最后一个节点的右子树为等于flattenTree(root的右子树),同时root的左子树为NULL。
附上代码:
/**
* 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 == NULL )
return ;
root = flattenTree ( root ) ;
}
TreeNode* flattenTree ( TreeNode* root )
{
if ( root == NULL )
return root ;
if ( root -> left == NULL )
{
root -> right = flattenTree ( root -> right ) ;
return root ;
}
TreeNode* temp = root -> right ;
root -> right = flattenTree ( root -> left ) ;
TreeNode* t = root ;
while ( t -> right != NULL )
t = t -> right ;
t -> right = flattenTree ( temp ) ;
root -> left = NULL ;
return root ;
}
};