码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Flatten Binary Tree to Linked List

时间:2014-08-26 22:57:46      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   strong   for   ar   div   

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 };

 

LeetCode: Flatten Binary Tree to Linked List

标签:style   blog   http   color   io   strong   for   ar   div   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_flatten_binary_tree_to_linked_list.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!