[LeetCode] 031: Flatten Binary Tree to Linked List

来源:互联网 发布:免费视频监控软件 编辑:程序博客网 时间:2024/06/05 16:56
[Problem]

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.


[Solution]
/**
* 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, TreeNode* &head, TreeNode* &tail){
// null node
if(root == NULL){
head = NULL;
tail = NULL;
return;
}

// flatten the left brunch and the right brunch
TreeNode *leftHead = NULL;
TreeNode *leftTail = NULL;
TreeNode *rightHead = NULL;
TreeNode *rightTail = NULL;
flatten(root->left, leftHead, leftTail);
flatten(root->right, rightHead, rightTail);

// set result
if(leftHead == NULL){
if(rightHead == NULL){
root->left = NULL;
root->right = NULL;
head = root;
tail = root;
}
else{
root->left = NULL;
root->right = rightHead;
head = root;
tail = rightTail;
}
}
else{
if(rightHead == NULL){
root->left = NULL;
root->right = leftHead;
head = root;
tail = leftTail;
}
else{
root->left = NULL;
root->right = leftHead;
leftTail->right = rightHead;
head = root;
tail = rightTail;
}
}
}
// flatten a sub-tree
void flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *head = NULL;
TreeNode *tail = NULL;
flatten(root, head, tail);
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击