Flatten Binary Tree to Linked List
Oct 14 '12
7105 / 21371
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:
» Solve this problem
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
按照道理应该1更快,但是实际貌似差不多。
1和2的区别,主要是在对flat( right,xx)的处理上。
/**
* Definition for binary tree
* 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;
TreeNode* tail;
flat(root, tail);
}
void flat(TreeNode* cur, TreeNode* &tail) {
if (cur->left == NULL && cur->right == NULL) {
tail = cur;
return;
}
if (cur->left != NULL) {
TreeNode* lefttail;
flat(cur->left, lefttail);
lefttail->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
if (lefttail->right == NULL)
tail = lefttail;
else {
flat(lefttail->right, tail);
}
}
else {
flat(cur->right, tail);
}
}
};
/**
* Definition for binary tree
* 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;
TreeNode* tail;
flat(root, tail);
}
void flat(TreeNode* cur, TreeNode* &tail) {
if (cur->left == NULL && cur->right == NULL) {
tail = cur;
return;
}
if (cur->left != NULL) {
TreeNode* lefttail;
flat(cur->left, lefttail);
lefttail->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
flat(cur->right, tail);
}
};

本文介绍了如何通过递归方法将二叉树转换为链表,确保每个节点的右指针指向下一个节点,遵循前序遍历顺序。详细解释了算法的实现步骤和关键细节。
822

被折叠的 条评论
为什么被折叠?



