LeetCode: 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
地址:https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/
算法:题目要求按先序顺序把二叉树拉成一条链表。可以用递归解决,其中函数subFlatten表示用于解决以root为根的二叉树,并且返回结果链表的头尾节点。有了这个头尾节点,那么解决起来就比较简单了。代码:
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 void flatten(TreeNode *root) {
13 subFlatten(root);
14 }
15 pair<TreeNode *, TreeNode *> subFlatten(TreeNode *root){
16 if(!root){
17 TreeNode *temp = NULL;
18 return make_pair(temp,temp);
19 }
20 TreeNode *left_p = root->left;
21 TreeNode *right_p = root->right;
22 root->left = root->right = NULL;
23 TreeNode *firstNode = root;
24 TreeNode *lastNode = root;
25 pair<TreeNode *, TreeNode *> first_last_pair = subFlatten(left_p);
26 if(first_last_pair.first){
27 lastNode->right = first_last_pair.first;
28 lastNode = first_last_pair.second;
29 }
30 first_last_pair = subFlatten(right_p);
31 if(first_last_pair.first){
32 lastNode->right = first_last_pair.first;
33 lastNode = first_last_pair.second;
34 }
35 return make_pair(firstNode,lastNode);
36 }
37 };