Flatten Binary Tree to Linked List
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
解题思路:
题意为将二叉树依照先序遍历压平。
最開始时对in-place理解错误,以为空间复杂度仅仅能为O(1)。事实上不然(我们姑且觉得递归的时候空间不变)。
我们能够用递归来解决问题。
首先定义个递归函数,改递归函数返回root为根节点的最右节点。
倘若root->left不为空。则将左子树的节点插入到root->right中。
递归代码例如以下:
/**
* 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) {
flattenHelper(root);
}
//返回root为根的最右边的那个节点
TreeNode* flattenHelper(TreeNode* root){
if(root == NULL){
return NULL;
}
TreeNode* leftMost = flattenHelper(root->left);
TreeNode* rightMost = flattenHelper(root->right);
if(leftMost!=NULL){
TreeNode* temp = root->right;
root->right = root->left;
root->left = NULL;
leftMost->right = temp;
}
if(leftMost==NULL&&rightMost==NULL){
return root;
}else if(rightMost==NULL){
return leftMost;
}else{
return rightMost;
}
}
};
浙公网安备 33010602011771号