您的位置:首页 > 其它

[Leetcode 81] 114 Flatten Binary Tree to Linked List

2013-07-23 14:19 555 查看
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


Analysis:

Solution to tree problem is always recursive. So is this problem. First let's see some basic cases:

For node with left and right all equals NULL, we just need to return the node itself;

For a simplest tree [a, b, c], we must return the a b c sequence.

The rule is that, a is the first node of the flattened list, and the left child b is the next and the right child c is the last.

Then, we expand it to general cases: [root, left-tree, right-tree]

  1. root should always be the first node.

  2. the flatterned left-tree is the next of root.

  3. the flatterned right-tree is the next of the last node of the flatterned left-tree.

So, we can see that the need variables are the first and last node of the flatterned list.

How to return two variables in one function? We can return the first node and use an extra function argument to achieve this.

Code:

/**
* 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 *h;
if (root != NULL)
ftHelper(root, &h);
}

TreeNode *ftHelper(TreeNode* node, TreeNode **llast) {
TreeNode *last = node, *first = node;
*llast = node;

if (node->left == NULL && node->right == NULL)
return node;

TreeNode *l = node->left, *r = node->right, *h;

if (l != NULL) {
node->right = ftHelper(l, &last);
node->left = NULL;
}

if (r != NULL) {
last->right = ftHelper(r, &h);
last = h;
}

*llast = last;
return first;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: