您的位置:首页 > 编程语言 > C语言/C++

[LeetCode] Flatten Binary Tree to Linked List

2015-08-11 18:03 302 查看


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


click to show hints.

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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode